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"
    
  • 相关阅读:
    spirngmvc整合mybatis
    C#微信支付
    centos mysql数据库主从同步
    centos 搭建ftp
    修改 Docker 默认网桥地址
    安装docker
    脚本自动化装centos6.5 python2.6升级2.7
    centos6.5 python2.6升级2.7
    weblogic 安装及发布web应用
    centos6.5安装pip方法
  • 原文地址:https://www.cnblogs.com/pinked/p/12903623.html
Copyright © 2011-2022 走看看