Spring Boot Redis集成

作者: devilbb | 来源:发表于2019-06-27 18:06 被阅读0次

    Spring Boot Redis使用

    添加依赖

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

    配置Redis 地址

    spring:
      redis:
        host: localhost
        port: 6379
        database: 0
    

    配置RedisTemplate

    @Configuration
    public class RedisConfig {
    
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(connectionFactory);
    
            //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
            Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
    
            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            serializer.setObjectMapper(mapper);
    
            template.setValueSerializer(serializer);
            //使用StringRedisSerializer来序列化和反序列化redis的key值
            template.setKeySerializer(new StringRedisSerializer());
            template.afterPropertiesSet();
            return template;
        }
    }
    

    使用

    @RestController
    @RequestMapping(value = "/api/user")
    public class UserController {
    
        @Resource
        private RedisTemplate<String, Object> redisTemplate;
        
        @RequestMapping(value = "/addToRedis", method = RequestMethod.GET)
        public Object addToRedis() {
    
            UserDO record = new UserDO();
            record.setCreator("moshenglei");
            record.setGmtCreated(new Date());
            record.setModifier("moshenglei");
            record.setGmtModified(new Date());
            record.setIsDeleted("N");
            record.setName("莫胜磊");
    
            redisTemplate.opsForValue().set("haha", record);
            return "success";
        }
    
    
    
        @RequestMapping(value = "/getFromRedis", method = RequestMethod.GET)
        public Object getFromRedis() {
            UserDO record = (UserDO)redisTemplate.opsForValue().get("haha");
            return record;
        }
    }
    
    

    相关文章

      网友评论

        本文标题:Spring Boot Redis集成

        本文链接:https://www.haomeiwen.com/subject/jofdcctx.html