SpingCache简单使用

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: SpingCache

导入

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>

配置

在配置文件中加入

spring: cache:  type: redis                                             # 缓存类型  redis:   time-to-live: 36000000                                # 设置过期时间   cache-null-values: true                               # 防止缓存穿透

编写一个配置类,配置序列化规则

@Configuration@EnableCaching@EnableConfigurationProperties(CacheProperties.class)
publicclassCacheConfig {
@BeanpublicRedisCacheConfigurationcreateConfiguration(CachePropertiescacheProperties) {
CacheProperties.RedisredisProperties=cacheProperties.getRedis();
RedisCacheConfigurationconfig=RedisCacheConfiguration.defaultCacheConfig();
config=config.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(newStringRedisSerializer()));
config=config.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(newGenericFastJsonRedisSerializer()));
if (redisProperties.getTimeToLive() !=null) {
config=config.entryTtl(redisProperties.getTimeToLive());
        }
if (redisProperties.getKeyPrefix() !=null) {
config=config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
if (!redisProperties.isCacheNullValues()) {
config=config.disableCachingNullValues();
        }
if (!redisProperties.isUseKeyPrefix()) {
config=config.disableKeyPrefix();
        }
returnconfig;
    }
}

使用

加上@Cacheable使用

@Cacheable(value= {"brand"}, key="#root.methodName")
publicList<Brand>listBrand(intpageNum, intpageSize) {
PageHelper.startPage(pageNum, pageSize);
returnbaseMapper.selectList(null);
}

这样在有缓存的情况下,就直接读取缓存,不会再去查询数据库,从而减轻服务器压力提高性能

相关实践学习
基于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
相关文章
|
4月前
|
存储 缓存 Java
【scoop】安装及基本使用
【scoop】安装及基本使用
193 0
|
11月前
rChart安装及最简单使用
rChart安装及最简单使用
|
12月前
QWebEngineView简单使用
QWebEngineView是提供一个访问web页面的widget,这里是一个简单的使用代码
133 0
ApplicationEventPublisher的简单使用
ApplicationEventPublisher的简单使用
331 0
MPPlayer的简单使用
MPPlayer的简单使用
152 0
|
Web App开发 存储 监控
【ChromeDevTool】Performace的简单使用
【ChromeDevTool】Performace的简单使用
【ChromeDevTool】Performace的简单使用
|
Java 程序员
断点调试基本使用
断点调试基本使用
186 0
断点调试基本使用
|
测试技术 数据安全/隐私保护