springboot配置redis最简单例子
解决方法:
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
2、在启动类Application中添加一下配置
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) throws UnknownHostException {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(factory);
return template;
}
3、保存数据到缓存例子
StringRedisTemplate stringRedisTemplate=(StringRedisTemplate)SpringUtil.getBean(StringRedisTemplate.class);
stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
Iterator var2 = list.iterator();//list是从数据库读出来的数据
while(var2.hasNext()) {
Object obj = var2.next();
if (obj != null) {
String key = "id";
redisConnection.set(key.getBytes(), JSON.toJSONString(obj).getBytes(), Expiration.seconds(expirationTime), SetOption.UPSERT);
}
}
return null;
}
4、读取缓存例子
StringRedisTemplate stringRedisTemplate=(StringRedisTemplate)SpringUtil.getBean(StringRedisTemplate.class);
List<String> vals =stringRedisTemplate.opsForValue().multiGet(realKeys);
realKeys是键(id值的集合)的list集合