基本使用
依赖和配置
依赖
org.springframework.boot spring-boot-starter-data-redis
配置
spring: redis: database: 0 host: localhost port: 6379 password: jedis: pool: max-active: 8 #=最大连接数(使用负值表示没有限制) max-wait: -1s #最大阻塞时间(使用负值表示没有限制) max-idle: 8 #最大空闲连接 min-idle: 0 #最小空闲连接 timeout: 10s
使用
@RestController@RequestMapping("/redis")public class RedisResource { @Autowired private StringRedisTemplate stringRedisTemplate; @PostMapping("/test") public String test(@RequestParam(defaultValue = "key") String key, @RequestParam(defaultValue = "val") String val) { stringRedisTemplate.opsForValue().set(key, val); return "key:" + key + ", val=" + stringRedisTemplate.opsForValue().get(key); }}
测试
写个启动类,启动后访问
查看redis
$ telnet localhost 6379Trying ::1...Connected to localhost.Escape character is '^]'.$ get aabc
CacheManager缓存管理
使用cacheManager,结合spring可以使用@Cacheable
、@CachePut
、@CacheEvict
添加到方法上面,来基于方法参数和返回值看来操作缓存
RedisConfig配置
@Configuration@EnableCachingpublic class RedisCachingConfigurer extends CachingConfigurerSupport { private static final Duration timeToLive = Duration.ZERO; @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializerredisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解决乱码的问题) RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(timeToLive) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; }}
注解操作缓存
@Service@Slf4jpublic class UserService { private Mapdata = new ConcurrentHashMap<>(10); //添加缓存 @Cacheable(value = "userCache", key = "#id", unless = "#result==null") public User get(int id){ log.info("不走redis缓存,查询用户,id={}", id); return data.get(id); } //修改缓存 @CachePut(value = "userCache", key = "#id") public User save(int id, String name){ data.put(id, new User(id, name)); return data.get(id); } //删除缓存 @CacheEvict(value = "userCache", key = "#p0") public void del(int id){ data.remove(id); } @Data @AllArgsConstructor @NoArgsConstructor public static class User implements Serializable{ private int id; private String name; }}
接口测试
@RestController@RequestMapping("/redis")public class RedisResource { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private UserService userService; @PostMapping("/test") public String test(@RequestParam(defaultValue = "key") String key, @RequestParam(defaultValue = "val")String val){ stringRedisTemplate.opsForValue().set(key, val); return "key:" + key + ", val=" + stringRedisTemplate.opsForValue().get(key); } /**--------------cacheManager测试--------------*/ @GetMapping("/user") public UserService.User get(int id){ return userService.get(id); } @PostMapping("/user") public UserService.User save(int id, String name){ return userService.save(id, name); } @DeleteMapping("/user") public String del(int id){ userService.del(id); return "delete success."; }}
启动项目后,测试。第一次redis没有任何缓存值
GET http://localhost:8080/redis/user?id=1
控制台打印:
[nio-8080-exec-4] c.yimingkeji.redis.service.UserService : 不走redis缓存,查询用户,id=1
然后调用post方法来添加缓存
POST http://localhost:8080/redis/user?id=1&name=哈哈哈
{ "id": 1, "name": "哈哈哈"}
再次查询
GET http://localhost:8080/redis/user?id=1
{ "id": 1, "name": "哈哈哈"}
查看redis
然后再调用delete方法删除缓存
DELETE http://localhost:8080/redis/user?id=1
再次查看redis