zoukankan      html  css  js  c++  java
  • Springboot整合Redis

    Springboot整合Redis

    依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    • 在springboot2.x之后, 原来使用的jedis被替换成了lettuce

    配置

    spring:
      redis:
        host: 127.0.0.1
        port: 6379
    

    测试

    @Autowired
    private RedisTemplate redisTemplate;
    
    @Test
    void contextLoads() {
        redisTemplate.opsForValue().set("key1", "aaa");
        System.out.println(redisTemplate.opsForValue().get("key1"));
    }
    
    127.0.0.1:6379> keys *
    1) "xacxedx00x05tx00x05user1" 
    

    通过自定义RedisTemplate, 使数据序列化

    @Configuration
    public class RedisConfig {
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) throws UnknownHostException {
            //默认是<Object, Object>
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(factory);
    
            //json序列化配置
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(mapper);
            //string序列化
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            //key采用string序列化
            template.setKeySerializer(stringRedisSerializer);
            template.setHashKeySerializer(stringRedisSerializer);
            //value采用json序列化
            template.setValueSerializer(jackson2JsonRedisSerializer);
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
    
            return template;
        }
    }
    

    再次测试后

    127.0.0.1:6379> keys *
    1) "xacxedx00x05tx00x05user1"
    2) "user1"
    
  • 相关阅读:
    [状压dp][spfa] Jzoj P3737 挖宝藏
    [计算几何] Jzoj P3736 数学题
    [排序][vector] Jzoj P6288 旋转子段
    [区间dp] Jzoj P6287 扭动的树
    [bfs][spfa] Jzoj P6286 走格子
    [点分治] Luogu P2664 树上游戏
    [树链剖分][树状数组] Luogu P3676 小清新数据结构题
    [计算几何][dp] Luogu P1995 智能车比赛
    [后缀数组][并查集] Luogu P2178 品酒大会
    [莫比乌斯反演][整除分块] Bzoj P2301 Problem b
  • 原文地址:https://www.cnblogs.com/pinked/p/12903623.html
Copyright © 2011-2022 走看看