ssm框架使用redis的示例:
1.導入Redis相關jar包,代碼:
<!-- redis相關 --><dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
2.在redis.properties文件中寫入Redis基本配置屬性,代碼:
# 服務器ipredis.hostname = 127.0.0.1
# redis數據庫端口
redis.port = 6379
# 使用的數據庫(共有16個數據庫0~15)
redis.database = 2
# 控制一個pool可分配多少個jedis示例
redis.pool.maxActive = 50
# 控制一個pool最多有多少個狀態為idle的jedis實例
redis.pool.maxIdle = 300
# 最大等待連接時間(單位毫秒)
redis.pool.maxTotal = 600
# redis密碼(一般不設置密碼,設了重啟服務也會沒有)
redis.pass =
3.在applicationContext.xml中添加相關bean,代碼:
<!-- 載入配置文件 --><context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>
<!-- 配置JedisPoolConfig示例 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.pool.maxIdle}"/>
<property name="maxTotal" value="${redis.pool.maxTotal}"/>
</bean>
<!-- 配置JedisConnectionFactory -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.hostname}"/>
<property name="port" value="${redis.port}"/>
<property name="password" value="${redis.pass}"/>
<property name="database" value="${redis.database}"/>
<property name="poolConfig" ref="poolConfig"/>
<property name="usePool" value="true"/>
</bean>
<!-- 配置RedisTemplate-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"/>
<property name="defaultSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
</bean>
4.自動注入RedisTemplate并使用,代碼:
@Autowiredprivate RedisTemplate redisTemplate;
@Override
public Account getAccountById(Integer id) {
if(redisTemplate.opsForHash().hasKey("Account",id.toString())){
//redis緩存中包含數據,則從redis中獲取
System.out.println("從redis中獲取");
return (Account) redisTemplate.opsForHash().get("Account",id.toString());
} else {
//redis緩存中不含該數據,則從mysql中獲取
System.out.println("從mysql中獲取");
return accountDao.getAccountById(id);
}
}