springboot系列十 Spring-Data-Redis

基本使用

依赖和配置

依赖java

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

配置git

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

测试

写个启动类,启动后访问 http://localhost:8080/redis/test?key=a&val=abcredis

查看redisspring

$ telnet localhost 6379
Trying ::1...
Connected to localhost.
Escape character is '^]'.

$ get a
abc

CacheManager缓存管理

使用cacheManager,结合spring可使用@Cacheable@CachePut@CacheEvict添加到方法上面,来基于方法参数和返回值看来操做缓存json

RedisConfig配置

@Configuration
@EnableCaching
public class RedisCachingConfigurer extends CachingConfigurerSupport {

    private static final Duration timeToLive = Duration.ZERO;

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = 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
@Slf4j
public class UserService {

    private Map<Integer, User> data = 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

控制台打印:springboot

[nio-8080-exec-4] c.yimingkeji.redis.service.UserService   : 不走redis缓存,查询用户,id=1

而后调用post方法来添加缓存app

POST http://localhost:8080/redis/user?id=1&name=哈哈哈
{
    "id": 1,
    "name": "哈哈哈"
}

再次查询less

GET http://localhost:8080/redis/user?id=1
{
    "id": 1,
    "name": "哈哈哈"
}

查看redisspring-boot

而后再调用delete方法删除缓存

DELETE http://localhost:8080/redis/user?id=1

再次查看redis

项目源码

https://gitee.com/yimingkeji/springboot/tree/master/redis

相关文章
相关标签/搜索