精通SpringBoot——第七篇:整合Redis实现缓存

本文涉及的产品
云原生内存数据库 Tair,内存型 2GB
云数据库 Redis 版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: springboot 整合Redis实现缓存

项目中用到缓存是很常见的事情, 缓存能够提升系统访问的速度,减轻对数据库的压力等好处。今天我们来讲讲怎么在spring boot 中整合redis 实现对数据库查询结果的缓存。
首先第一步要做的就是在pom.xml文件添加spring-boot-starter-data-redis。
要整合缓存,必不可少的就是我们要继承一个父类CachingConfigurerSupport。我们先看看这个类的源码

public class CachingConfigurerSupport implements CachingConfigurer {
    // Spring's central cache manage SPI ,
    @Override
    @Nullable
    public CacheManager cacheManager() {
        return null;
    }
    //key的生成策略
    @Override
    @Nullable
    public KeyGenerator keyGenerator() {
        return null;
    }
    //Determine the Cache instance(s) to use for an intercepted method invocation.
    @Override
    @Nullable
    public CacheResolver cacheResolver() {
        return null;
    }
    //缓存错误处理
    @Override
    @Nullable
    public CacheErrorHandler errorHandler() {
        return null;
    }

}

RedisConfig类

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }

    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }


    public class Receiver {
        private CountDownLatch latch;

        @Autowired
        public Receiver(CountDownLatch latch) {
            this.latch = latch;
        }

        public void receiveMessage(String message) {
            latch.countDown();
        }
    }


    @Bean
    public KeyGenerator myKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append(method.getName());
                for (Object obj : objects) {
                    sb.append(JSON.toJSONString(obj));
                }
                return sb.toString();
            }
        };
    }

    /**
     * @param redisConnectionFactory
     * @return
     * @// TODO: 2018/4/27 redis fastjson序列化
     */
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        //使用fastjson序列化
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        // 全局开启AutoType,不建议使用
        // ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        // 建议使用这种方式,小范围指定白名单
        ParserConfig.getGlobalInstance().addAccept("com.developlee.models.");
        // value值的序列化采用fastJsonRedisSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        // key的序列化采用StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    /**
     * @return
     * @// TODO: 2018/4/27 设置redis 缓存时间 5 分钟
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
        configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofMinutes(5));
        return configuration;
    }
}

这段代码中,重点关注对象是RedisTemplate 和StringRedisTemplate还有RedisMessageListenerContainer,RedisTemplate和StringRedisTemplate设置了一些序列化的参数和指定序列化的范围(主要为了防止黑客利用Redis的序列化漏洞),@ConditionalOnMissingBean注解的意思就是如果容器中没有这个类型Bean就选择当前Bean。RedisMessageListenerContainer是为Redis消息侦听器提供异步行为的容器,主要处理低层次的监听、转换和消息发送的细节。

再来看看application.xml我们的配置 , so easy~~

spring:
   redis:
     database: 0  # Redis数据库索引(默认为0)
     host: 192.168.0.100 # Redis服务器地址 (默认为127.0.0.1)
     port: 6379    # Redis服务器连接端口 (默认为6379)
     password: 123456   # Redis服务器连接密码(默认为空)
     timeout: 2000  # 连接超时时间(毫秒)
  cache:
    type: redis

接下来我们就可以使用Redis缓存了,在Service层我们用注解@Cacheable来缓存查询的结果。

    @Cacheable(value= "orderDetailCache", keyGenerator = "myKeyGenerator", unless = "#result eq null")
    public OrderDetailEntity findOrderDetail(OrderDetailEntity orderDetailEntity) {
        return orderDetailDao.findEntity(orderDetailEntity);
    }

到这里我们就已经整合了Redis缓存了,是不是很简单的呢?自己多动手尝试哦!

最后,以上示例代码可在我的github.com中找到。
我的个人公众号:developlee的潇洒人生。
关注了也不一定更新,更新就不得了了。
qrcode_for_gh_2bd3f44efa21_258

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
6天前
|
canal 缓存 NoSQL
Redis缓存与数据库如何保证一致性?同步删除+延时双删+异步监听+多重保障方案
根据对一致性的要求程度,提出多种解决方案:同步删除、同步删除+可靠消息、延时双删、异步监听+可靠消息、多重保障方案
Redis缓存与数据库如何保证一致性?同步删除+延时双删+异步监听+多重保障方案
|
6天前
|
存储 NoSQL Redis
SpringCloud基础7——Redis分布式缓存,RDB,AOF持久化+主从+哨兵+分片集群
Redis持久化、RDB和AOF方案、Redis主从集群、哨兵、分片集群、散列插槽、自动手动故障转移
SpringCloud基础7——Redis分布式缓存,RDB,AOF持久化+主从+哨兵+分片集群
|
17天前
|
缓存 NoSQL 关系型数据库
MySQL与Redis缓存一致性的实现与挑战
在现代软件开发中,MySQL作为关系型数据库管理系统,广泛应用于数据存储;而Redis则以其高性能的内存数据结构存储特性,常被用作缓存层来提升数据访问速度。然而,当MySQL与Redis结合使用时,确保两者之间的数据一致性成为了一个重要且复杂的挑战。本文将从技术角度分享MySQL与Redis缓存一致性的实现方法及其面临的挑战。
41 2
|
19天前
|
Java UED Maven
紧跟技术潮流:手把手教你构建响应式Vaadin应用,让用户体验无缝接轨!
【8月更文挑战第31天】本文从零开始,详细介绍如何使用强大的Java框架Vaadin构建流畅且响应式的Web应用程序。首先,确保安装JDK 1.8+、Maven 3.3.9+及IDE。接着,创建Maven项目并添加Vaadin依赖。然后,通过继承`UI`类创建主界面,并定义自定义主题与样式。利用Vaadin的响应式布局组件,如`HorizontalLayout`和`VerticalLayout`,实现多设备兼容性。
27 0
|
19天前
|
缓存 NoSQL Redis
Entity Framework Core 与 Redis 强强联手!实现高速缓存,提升应用性能超厉害
【8月更文挑战第31天】在现代应用开发中,结合 Entity Framework Core 与 Redis 可显著提升数据访问速度。Entity Framework Core 是一个强大的 ORM 框架,但处理频繁访问的数据时可能遇到性能瓶颈。Redis 作为高性能内存数据库,具备快速读写能力。两者结合利用 Redis 高速缓存,减少直接数据库访问,提高应用响应速度及性能。
31 0
|
26天前
|
缓存 NoSQL 网络安全
【Azure Redis 缓存】Azure Redis服务开启了SSL(6380端口), PHP如何访问缓存呢?
【Azure Redis 缓存】Azure Redis服务开启了SSL(6380端口), PHP如何访问缓存呢?
|
26天前
|
缓存 NoSQL Redis
【Azure Redis 缓存】Redission客户端连接Azure:客户端出现 Unable to send PING command over channel
【Azure Redis 缓存】Redission客户端连接Azure:客户端出现 Unable to send PING command over channel
|
26天前
|
存储 缓存 NoSQL
【Azure Redis 缓存】关于Azure Cache for Redis 服务在传输和存储键值对(Key/Value)的加密问题
【Azure Redis 缓存】关于Azure Cache for Redis 服务在传输和存储键值对(Key/Value)的加密问题
|
26天前
|
缓存 NoSQL Redis
【Azure Redis 缓存】Redis 连接失败
【Azure Redis 缓存】Redis 连接失败
|
26天前
|
缓存 NoSQL 网络协议
【Azure Redis 缓存】Lettuce 连接到Azure Redis服务,出现15分钟Timeout问题
【Azure Redis 缓存】Lettuce 连接到Azure Redis服务,出现15分钟Timeout问题
【Azure Redis 缓存】Lettuce 连接到Azure Redis服务,出现15分钟Timeout问题