码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot2.x 整合Redis和使用Redis缓存

时间:2020-06-13 10:31:13      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:get   ble   控制台   vat   learn   strong   ext   wired   exce   

SpringBoot2.x 整合Redis和使用Redis缓存

导入依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

以默认的方式(jdk序列化)存储对象

技术图片

配置序列化器,以json格式存储

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    //配置Redistemplate
    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(objectMapper);

        // 设置value的序列化规则和 key的序列化规则
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();

        return template;
    }

    //使用CacheManager缓存
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 配置序列化(解决乱码的问题),过期时间30秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(1800000))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

技术图片

将Redis中的数据反序列化返回到前端页面

编写Controller

@RestController
public class EmployeeController {
    /**
     * 服务对象
     */
    @Resource
    private EmployeeService employeeService;

   //@Autowired
    //private RedisTemplate redisTemplate;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/emp/{id}")
    @Cacheable(cacheNames = {"emp"})  //使用缓存
    public Employee selectOne(@PathVariable("id") Integer id) {
        System.out.println("查询了"+id+"号员工");
        return this.employeeService.queryById(id);
    }
}

进行访问
技术图片

看控制台输出
技术图片

我们可以看出进行了数据库的查询

清空控制台,我们再次进行访问
技术图片

说明确实走了Redis缓存

本篇随笔参考[SpringBoot2.x整合redis和使用redis缓存](https://www.cnblogs.com/Neil-learning/p/12637711.html)

SpringBoot2.x 整合Redis和使用Redis缓存

标签:get   ble   控制台   vat   learn   strong   ext   wired   exce   

原文地址:https://www.cnblogs.com/gttttttt/p/13111690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!