redis:
host: 172.27.15.23
port: 6379
database: 0
pool:
max-idle: 20
min-idle: 1
max-active: 20
max-wait: 60000
import org.springframework.cache.CacheManager
import org.springframework.cache.annotation.EnableCaching
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.cache.RedisCacheManager
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate){
redisTemplate.setKeySerializer(new GenericJackson2JsonRedisSerializer())
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer())
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate)
return redisCacheManager
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis 替换默认的序列化key 和value 的对象,解决服务器读取乱码。(不一定必须解决这个问题,只用于服务器读取直观显示。)
* @time 2017年11月22日 上午11:00:53
**/
@Configuration
public class RedisConfig {
@Autowired
private RedisTemplate redisTemplate;
@Bean
public RedisTemplate redisTemplateInit() {
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
@Test
public void saveMobileCodeInRedis(){
String mobile = "15818232009";
String code = "654321";
Long timeout = new Long(600);
ValueOperations<String, String> operations = redisTemplate.opsForValue();
if(! redisTemplate.hasKey(mobile)) {
System.out.println("写入缓存");
operations.set(mobile, code, timeout, TimeUnit.SECONDS);
}
if(redisTemplate.hasKey(mobile)){
if(operations.get(mobile).equals(code)){
System.out.println("成功");
Long time = redisTemplate.getExpire(mobile, TimeUnit.MILLISECONDS);
System.out.println("过期时间剩余(ms)=="+time+"ms");
}
}
}
@Test
@Ignore
public void testRedis() {
print();
}
private List print() {
ValueOperations<String, List> list = redisTemplate.opsForValue();
List<Department> results = list.get("departments:info:all");
for (Department d : results) {
System.out.println(d);
}
return results;
}
private void setDepartmentsInRedis() {
List<Department> departments = departmentMapper.selectAll();
redisTemplate.opsForValue().set("echo:department:all", departments, 200, TimeUnit.SECONDS);
}