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);
}
}