Spring data redis

Basic use

Dependencies and configuration

rely on

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

To configure

spring:
  redis:
    database: 0
    host: localhost
    port: 6379
    password:
    jedis:
      pool:
        max-active: 8 #=Maximum connections (use negative to indicate no limit)
        max-wait: -1s #Maximum blocking time (use a negative value to indicate no limit)
        max-idle: 8 #Maximum free connection
        min-idle: 0 #Minimum free connection
    timeout: 10s

Use

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

test

Write a startup class and access it after startup http://localhost:8080/redis/test?key=a&val=abc

View redis

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

$ get a
abc

CacheManager cache management

With cacheManager and spring, you can add @ Cacheable, @ CachePut, @ CacheEvict to a method to operate the cache based on the method parameters and return values

RedisConfig configuration

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

        //Solve the problem of query cache conversion exception
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // Configure serialization (to solve the problem of garbled code)
        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;
    }
}

Annotation operation cache

@Service
@Slf4j
public class UserService {

    private Map<Integer, User> data = new ConcurrentHashMap<>(10);
    //Add cache
    @Cacheable(value = "userCache", key = "#id", unless = "#result==null")
    public User get(int id){
        log.info("Not go redis Cache, query users, id={}", id);
        return data.get(id);
    }
    //Modify cache
    @CachePut(value = "userCache", key = "#id")
    public User save(int id, String name){
        data.put(id, new User(id, name));
        return data.get(id);
    }
    //Delete cache
    @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;
    }
}

Interface test

@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 Testing--------------*/
    @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.";
    }
}

After starting the project, test. The first redis has no cache value

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

Console printing:

 [nio-8080-exec-4] c.yimingkeji.redis.service.UserService: do not use redis cache, query users, id=1

Then call the post method to add caching.

POST http://Localhost: 8080 / redis / user? Id = 1 & name = hahaha
{
    "id": 1,
    "name": "Ha ha ha"
}

Query again

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

View redis

Then call the delete method to delete the cache

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

Check redis again

Project source code

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

Tags: Programming Redis Spring Database Jedis

Posted on Tue, 03 Dec 2019 12:17:53 -0800 by sparq