Home > Database > Redis > body text

How to use redis correctly in springboot

PHPz
Release: 2023-05-29 15:07:06
forward
699 people have browsed it

Redis implements data caching. In the project, some dictionary data, session data, and temporary data will be stored in redis. Springboot also supports redis. Generally speaking, multiple threads use one redis implementation. There is a risk of thread safety, and implementing one thread per thread is too wasteful of resources. It is very dangerous to be unable to control the number of threads, so some redis thread pool components have appeared. Let’s talk about the two main components.

jedis thread pool mainly means that each instance has its own thread, and the thread can be obtained from the pool it establishes
lettuce lettuce is a thread pool tool launched by Apache. Its redis instance can be used by multiple Thread shared access improves resource usage

redis serialization configuration

Generally speaking, redis-key uses string serialization; redis-value uses json serialization, and the size of json Small, highly readable, and does not need to implement the serializer interface.

/**
 * 对redis的配置.
 */
@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    /**
     * redis重写RedisTemplate.
     */
    @Bean
    public RedisTemplate redisTemplate() {
        RedisTemplate redisTemplate = new RedisTemplate();
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //序列化时允许非常量字段均输出类型,即redis序列化后带有类型
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // redis key的序列化
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);

        // redis value的序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}
Copy after login

In the above code, the json string generated by om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL) has a type, so that it can be directly inferred through the type when deserializing.

[
  "com.lind.basic.entity.Token",
  {
    "credentials": "ok",
    "region": "hello",
    "bucket": null
  }
]
Copy after login

Look at the code for adding and reading

 @GetMapping("set")
    public String set() throws JsonProcessingException {
        Token token = Token.builder()
                .credentials("ok")
                .region("hello")
                .build();
        redisTemplate.opsForValue().set("test:user", token);//redisTemplate帮我们序列化
        redisTemplate.opsForHash().put("author", "zzl", token);
        return "OK";
    }

    @GetMapping("get")
    public Token get() throws IOException {
        return (Token) redisTemplate.opsForValue().get("test:user");
    }
Copy after login

Note: For the entity class Token, it should have a no-argument constructor, which is required for deserialization.

The above is the detailed content of How to use redis correctly in springboot. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template