当前位置:网站首页>如丝般添加缓存来优化服务
如丝般添加缓存来优化服务
2022-06-10 08:29:00 【CodeJames】
如丝般添加缓存来优化服务
在一个项目在使用的过程中,随着数据或者用户的增多,慢慢就会了出现老化;当请求个别接口就出现了返回缓慢的情景,严重影响了用户的使用体验,随之就需要对服务进行优化升级。
优化不是我们重新去编写这个项目,而是用一些中间件去优化,常见的就是去缓存啦,因为很多时候我们的项目的瓶颈不是cpu等这些硬件,而是IO操作,因此对IO优化后会很好地提高项目能力。
添加redis的一般实现方式
在Java领域常见的就是添加redis缓存器来实现优化,如果手动去实现redis的话,我们首先要去写一个redisUtil的工具类,在我们需要添加缓存的地方把数据手动放到redis中;
redis的工具类:
@Service
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public Object get(final String key) {
return redisTemplate.opsForValue().get(key);
}
public void setWithTime(String key, Object obj, long minute) {
redisTemplate.opsForValue().set(key, obj, minute, TimeUnit.MINUTES);
}
public boolean putHash(String key, Object field, Object value) {
boolean result = false;
try {
redisTemplate.opsForHash().put(key, field, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public Object getHash(String key, Object field) {
return redisTemplate.opsForHash().get(key, field);
}
public void setExpire(String key, long timeout, TimeUnit unit) {
redisTemplate.expire(key, timeout, unit);
}
public boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
public void deleteKey(String key) {
redisTemplate.delete(key);
}
}
使用方式:
// token存入redis,设置过期时间
redisUtil.set("qq:music:" + sn + ":token", token);
redisUtil.setExpire("qq:music:" + sn + ":token", Long.parseLong(expiresIn) - 300L, TimeUnit.SECONDS);
这需要我们手动去实现,非常的麻烦。
那有没有比较丝滑的实现方式呢?
这里我们就引入了阿里开发的JetCache这个工具,JetCache是一个基于Java的缓存系统封装,提供统一的API和注解来简化缓存的使用。 JetCache提供了比SpringCache更加强大的注解,可以原生的支持TTL、两级缓存、分布式自动刷新,还提供了Cache接口用于手工缓存操作。
那如何实现呢?
首先是引入依赖:

接着就是配置,新建类:JetCacheConfig配置类
@Configuration
@EnableMethodCache(basePackages = "com.midea.ac.*.service")
@EnableCreateCacheAnnotation
public class JetCacheConfig {
@Bean
public Pool<Jedis> pool(){
GenericObjectPoolConfig pc = new GenericObjectPoolConfig();
pc.setMinIdle(2);
pc.setMaxIdle(10);
pc.setMaxTotal(10);
return new JedisPool(pc, "localhost", 6379);
}
@Bean
public SpringConfigProvider springConfigProvider() {
return new SpringConfigProvider();
}
@Bean
public GlobalCacheConfig config(SpringConfigProvider configProvider, Pool<Jedis> pool){
Map localBuilders = new HashMap();
EmbeddedCacheBuilder localBuilder = LinkedHashMapCacheBuilder
.createLinkedHashMapCacheBuilder()
.keyConvertor(FastjsonKeyConvertor.INSTANCE);
localBuilders.put(CacheConsts.DEFAULT_AREA, localBuilder);
Map remoteBuilders = new HashMap();
RedisCacheBuilder remoteCacheBuilder = RedisCacheBuilder.createRedisCacheBuilder()
.keyConvertor(FastjsonKeyConvertor.INSTANCE)
.valueEncoder(JavaValueEncoder.INSTANCE)
.valueDecoder(JavaValueDecoder.INSTANCE)
.jedisPool(pool);
remoteBuilders.put(CacheConsts.DEFAULT_AREA, remoteCacheBuilder);
GlobalCacheConfig globalCacheConfig = new GlobalCacheConfig();
globalCacheConfig.setConfigProvider(configProvider);
globalCacheConfig.setLocalCacheBuilders(localBuilders);
globalCacheConfig.setRemoteCacheBuilders(remoteBuilders);
//日志输出统计信息
globalCacheConfig.setStatIntervalMinutes(15);
globalCacheConfig.setAreaInCacheName(false);
return globalCacheConfig;
}
}
其中注解@EnableMethodCache中的路径,表示对该包下的方法添加缓存,@EnableCreateCacheAnnotation表示开启缓存注解;在如上的配置中使用了JavaValueEncoder.INSTANCE,因此实体类需要进行序列化,即实现Serializable这个接口。
以上配置好之后就是在方法上添加缓存注解啦
@Cached(expire = 120, name = "f.s.*.*.getbyapplianceid.", cacheType = CacheType.REMOTE)
public ApplianceFirmware getByApplianceId(Long applianceId, Byte type){
return applianceFirmwareDao.getByApplianceIdAndType(applianceId, type);
}
如上在该方法上添加了@Cached注解,过期时间为120s,使用redis缓存。打开redis发现可存在该key,并且key获取对应的value。

结束语
以上是我在项目里实现的添加redis,只是抛转引玉,更多参考:https://github.com/alibaba/jetcache
边栏推荐
- Research Report on underwater plasma cutting machine industry - market status analysis and development prospect forecast
- How is the computer network often disconnected? Start with these questions
- What happens when your Huaqiangbei earphone falls into the water? How to restore sound quality?
- Research Report on water jet cutting equipment industry - market status analysis and development prospect forecast
- Web 3: a new era of Internet development
- 2022.06.04学习内容
- Perfect life - role: ChenYuXin
- [lingo] solving equations
- Sqlserver restore failed (the database is in use and cannot gain exclusive access to the database)
- 高通平台中gpio简单操作和调试
猜你喜欢

软件测试|从HR那里冒险套路过来的面试经验,绝对加分项

The most comprehensive layer2 research summary in the current technology circle

伦敦旅游必去博物馆推荐:伦敦自然历史博物馆
![[cryptography] AES encryption and decryption](/img/a5/ad3fed3004646ca894d59cc22d2f11.png)
[cryptography] AES encryption and decryption

USB TYPE -A -B -C 接口

Guys, help me! Reinstall mysql, and the current root password appears when the password is set

泰国曼谷大城府被福布斯评为“后疫情时代最值得一去的城市”

被微软遗弃的神作《扫雷》,竟然被中国玩家玩出花?

wechat_微信小程序分包的配置

Implementation of a simplified MVVM
随机推荐
Industry application saves 5g? Don't think too much. It's still mobile phone users who save 5g
Elementary knowledge of optical flow method
大佬们,帮帮我吧!重装MySQL,到设置密码就出现current root password
Genesis public chain is determined to appear at the consensus 2022 Conference
Hospital blood bank management system source code blood bank source code blood bank management source code hospital source code
OS Experiment 6 [device management]
Wechat applet bidirectional data binding, parent-child parameter transfer
软件测试|从HR那里冒险套路过来的面试经验,绝对加分项
【Lingo】线性规划
How to use module export import: uncaught syntaxerror: cannot use import statement outside a module
什么样的对象适合自动化测试?
接口测试怎么进行,如何做好接口测试
If you want to change careers, why do you prefer software testing?
SqlServer不同数据库名的还原
Test: Cup
A wordle Pendant
2022.06.07学习内容
【密码学】AES加解密
Research Report on underwater plasma cutting machine industry - market status analysis and development prospect forecast
光流法浅学