Springboot2.x 集成redis

pom.xml 添加

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

yml 配置

spring:
redis:
#数据库索引
database: 0
host: 118.24.11.111
port: 6379
password: 123456
jedis:
pool:
#最大连接数
max-active: 8
#最大阻塞等待时间(负数表示没限制)
max-wait: -1
#最大空闲
max-idle: 8
#最小空闲
min-idle: 0
#连接超时时间
timeout: 10000
RedisTemplate 配置,重写key和value的序列化
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// 配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer); // key序列化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // value序列化
redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); // Hash value序列化
redisTemplate.afterPropertiesSet();
return redisTemplate; } }
public interface RedisService {

    void setObj(String key, Object obj, long timeout);

    Object getObj(String key);

}
@Service("redisService")
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate redisTemplate;
@Override
public void setObj(final String key, Object obj, long timeout) {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, obj, timeout, TimeUnit.SECONDS);
}
@Override
public Object getObj(final String key) {
Object o = redisTemplate.opsForValue().get(key);
return o;
} }

调用示例

@Override
public User selectByPrimaryKey(Integer id) throws Exception {
User user1 = (User)redisService.getObj("user" + id);
if(user1 == null){
User user = userMapper.selectByPrimaryKey(id);
redisService.setObj("user" + id, user, 1000*60*2);
return user;
}
return user1;
}
上一篇:《zw版·Halcon-delphi系列原创教程》简单的令人发指,只有10行代码的车牌识别脚本


下一篇:HDU 6199 2017沈阳网络赛 DP