前言
在java开发中,缓存技术是提高应用性能的关键手段之一。
今天,我们来聊聊java中的四种主流本地缓存技术,并通过实例代码帮助大家更好地理解和应用这些技术。
一、基础缓存实现
首先,我们从最基础的缓存实现讲起。
一个简单的缓存系统通常包括缓存实体类、添加、删除、查询和清除缓存的功能。
1. 缓存实体类
缓存实体类用于存储缓存的键值对以及过期时间。
代码如下:。
public class cacheentity {
private string cachekey;
private object cachevalue;
private long expiretime; // 过期时间戳
// 构造方法、getter和setter省略
}2. 缓存工具类
接下来,我们实现一个缓存工具类,使用concurrenthashmap作为存储结构,并通过定时任务清除过期数据。
import java.util.concurrent.*;
import java.util.map;
publicclasscacheutil {
privatefinalstatic map<string, cacheentity> cache_map = newconcurrenthashmap<>();
privatestaticscheduledexecutorserviceexecutorservice= executors.newsinglethreadscheduledexecutor();
static {
executorservice.scheduleatfixedrate(() -> {
longcurrenttime= system.currenttimemillis();
cache_map.values().removeif(entity -> entity.getexpiretime() < currenttime);
}, 0, 500, timeunit.milliseconds);
}
publicstaticvoidput(string key, object value, long expiretimeinseconds) {
longexpiretime= system.currenttimemillis() + expiretimeinseconds * 1000;
cache_map.put(key, newcacheentity(key, value, expiretime));
}
publicstatic object get(string key) {
cacheentityentity= cache_map.get(key);
if (entity == null || entity.getexpiretime() < system.currenttimemillis()) {
cache_map.remove(key);
returnnull;
}
return entity.getcachevalue();
}
publicstaticvoiddelete(string key) {
cache_map.remove(key);
}
publicstaticvoidclear() {
cache_map.clear();
}
}测试代码:
public class test {
public static void main(string[] args) throws interruptedexception {
cacheutil.put("name", "zzc", 10l);
system.out.println("第一次查询结果:" + cacheutil.get("name"));
thread.sleep(2000l);
system.out.println("第二次查询结果:" + cacheutil.get("name"));
}
}二、guava loadingcache
guava是google提供的一个java基础库,其中的loadingcache是一个强大的缓存工具。
1. 使用示例
import com.google.common.cache.*;
import java.util.concurrent.executionexception;
import java.util.concurrent.timeunit;
publicclasstest {
publicstaticvoidmain(string[] args)throws executionexception {
loadingcache<string, string> cache = cachebuilder.newbuilder()
.concurrencylevel(8)
.expireafterwrite(10, timeunit.seconds)
.build(newcacheloader<string, string>() {
@override
public string load(string key)throws exception {
return"default_value";
}
});
cache.put("name", "zzc");
stringnamevalue= cache.get("name");
stringagevalue= cache.get("age", () -> "default_age");
stringsexvalue= cache.get("sex", () -> "key 不存在");
system.out.println("namevalue: " + namevalue);
system.out.println("agevalue: " + agevalue);
system.out.println("sexvalue: " + sexvalue);
}
}在上面的代码中,当调用cache.get(key)方法时,如果缓存中不存在对应的key,则会通过cacheloader的load方法加载默认值。
三、springboot整合caffeine
caffeine是一个高性能的java缓存库,springboot提供了与caffeine的无缝整合。
1. 开启缓存功能
在启动类上添加@enablecaching注解。
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.cache.annotation.enablecaching;
@enablecaching
@springbootapplication
public class testapplication {
public static void main(string[] args) {
springapplication.run(testapplication.class, args);
}
}2. 配置缓存管理器
import com.github.benmanes.caffeine.cache.caffeine;
import org.springframework.cache.cachemanager;
import org.springframework.cache.annotation.enablecaching;
import org.springframework.cache.caffeine.caffeinecachemanager;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import java.util.concurrent.timeunit;
@configuration
@enablecaching
publicclasscacheconfig {
@bean("caffeinecachemanager")
public cachemanager cachemanager() {
caffeinecachemanagercachemanager=newcaffeinecachemanager("usercache");
cachemanager.getcache("usercache").getconfig().setcaffeine(caffeinecachebuilder());
return cachemanager;
}
caffeine<object, object> caffeinecachebuilder() {
return caffeine.newbuilder()
.expireafterwrite(10, timeunit.seconds)
.maximumsize(100);
}
}3. 使用缓存注解
import org.springframework.cache.annotation.cacheevict;
import org.springframework.cache.annotation.cacheable;
import org.springframework.stereotype.service;
@service
publicclassuserservice {
// 模拟数据库操作
private map<integer, user> usermap = newhashmap<>();
@cacheable(value = "usercache", key = "#id")
public user getuserbyid(integer id) {
// 假设从数据库获取用户数据
useruser=newuser();
user.setid(id);
user.setname("user" + id);
usermap.put(id, user);
return user;
}
@cacheevict(value = "usercache", key = "#id")
publicvoiddeleteuserbyid(integer id) {
usermap.remove(id);
}
}四、jetcache——阿里巴巴的分布式缓存框架
jetcache是阿里巴巴开源的一款基于spring和redis的分布式缓存框架,提供了强大的缓存抽象和注解支持。
1. 引入依赖
在pom.xml中添加jetcache依赖。
<dependency>
<groupid>com.alicp.jetcache</groupid>
<artifactid>jetcache-starter-redis</artifactid>
<version>最新版本号</version>
</dependency>2. 配置jetcache
在application.yml中配置jetcache。
jetcache:
stat:enable# 开启统计
remote:
default:
type:redis
keyconvertor:fastjson# 序列化方式
valueencoder:java
valuedecoder:java
poolconfig:
minidle:5
maxidle:20
maxtotal:50
host:localhost
port: 63793. 使用jetcache注解
import com.alicp.jetcache.anno.cachetype;
import com.alicp.jetcache.anno.cached;
import com.alicp.jetcache.anno.cacheupdate;
import com.alicp.jetcache.anno.cacheinvalidate;
import org.springframework.stereotype.service;
@service
publicclassuserservice {
@cached(name = "usercache", key = "#id", cachetype = cachetype.both)
public string getuser(int id) {
return"用户:" + id;
}
@cacheupdate(name = "usercache", key = "#id", value = "#user")
publicvoidupdateuser(int id, string user) {
system.out.println("更新用户:" + user);
}
@cacheinvalidate(name = "usercache", key = "#id")
publicvoiddeleteuser(int id) {
system.out.println("删除用户:" + id);
}
}jetcache支持本地缓存和远程缓存的组合,非常适合分布式系统。
总结
今天我们一起探索了java本地缓存的多种实现方式,从手写缓存到guava cache、caffeine、ehcache和jetcache。每种方式都有自己的特点和适用场景。
到此这篇关于java中本地缓存的4种实现方式的文章就介绍到这了,更多相关java本地缓存实现内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论