Springboot 集成 Ehcache 代码讲解
一些小微服务项目又要用到缓存,但是又不想搭建 Redis 等服务,那么可以快速的配置一个 Ehcache 即可。那么下面就分享下 Springboot 集成 Ehcache 的代码。我们这里用JCache(JSR-107)
注解的方式和手动的方式来讲解。
Maven 引入所需包
<!--开启Springboot cache 缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache 缓存 -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.1.1</version>
</dependency>
Springboot配置
首先在启动Application类中加上缓存注解@EnableCaching
。
@SpringBootApplication
//开启缓存
@EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Ehcache 配置文件
在 resources
下 创建 ehcache.xml
文件,文件内容如下:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.ehcache.org/v3"
xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
xsi:schemaLocation="
http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
<service>
<jsr107:defaults enable-statistics="true"/>
</service>
<!-- user 为该缓存名称 对应@Cacheable的属性cacheNames-->
<cache alias="weather_cache" >
<!-- 指定缓存 key 类型,对应@Cacheable的属性key -->
<key-type>java.lang.String</key-type>
<!-- 配置value类型 -->
<value-type>com.sojson.weather.api.demo.dto.WeatherDto</value-type>
<expiry>
<!-- 缓存 ttl,单位为分钟,现在设置的是2个小时 -->
<ttl unit="minutes">120</ttl>
</expiry>
<resources>
<!-- 分配资源大小 -->
<heap unit="entries">2000</heap>
<offheap unit="MB">100</offheap>
</resources>
</cache>
<!--这里可以配置N个 。。。。 不同的cache 根据业务情况配置-->
</config>
单个cache
标签可以配置多个,这里注意的一点是 ttl
设置。这个是很有用的功能。
在 application.yml
配置文件中配置:
指定jcache config
配置文件路径。
spring:
cache:
jcache:
config: classpath:ehcache.xml
Cache 使用讲解
缓存的对象必须支持序列化,因为 Ehcache 会在一定的规则下会序列化后存储到硬盘上,所以要implements Serializable。
另外这里这里就2点简单讲解使用的方法。
1、手动使用Ehcache。
首先Spring本身就定义了缓存接口Cache和管理缓存控制器 CacheManager 。由于名字比较大众化,注意引入路径。
org.springframework.cache.Cache
org.springframework.cache.CacheManager
直接在在需要使用的类中注入即可,再提醒一次注意引入的包路径,用 @Resource
不要用 @Autowired
。
@Resource
CacheManager cacheManager;
手动存储和获取对象,配合注释分析代码:
//获取所有cache 配置
//Collection<String> cacheNames = cacheManager.getCacheNames();
//获取缓存对象,"weather_cache" 就是 ehcache.xml 中 <cache> 标签的 alias
Cache cache = cacheManager.getCache("weather_cache");
//创建一个对象
WeatherDto dto = new WeatherDto();
dto.setMessage("测试内容");
//存入缓存
cache.put("key", dto);
//获取刚刚存入的值
Cache.ValueWrapper res = cache.get("key");
//如果没有或者过期就为null
if(null != res){
//这里获取 ehcache.xml 中 <cache> value-type 定义的类型,可以直接强转。
WeatherDto obj = (WeatherDto)res.get();
//输出
System.out.println(obj.getMessage());//测试内容
}
这里主要是注意如果Ehcache 配置文件中指定了存储的对象,那么这就可以直接强转,但是也只能存储这个类型的对象。
2、注解方式使用Ehcache
这个方式很 nice,可以直接注解到我们的方法上,再次查询如果缓存没过期,就直接返回缓存内容,这样 Ehcache 和数据库配合起来使用就非常方便。
直接上之前 免费天气API Demo中的代码:
@Component
@Slf4j
public class WeatherManager {
//请求连接地址
final static String SOJSON_WEATHER_URL = "http://t.weather.sojson.com/api/weather/city/{1}";
/**
* 获取数据
* @param id
* @return
*/
@Cacheable(cacheNames = "weather_cache", key = "#id")// 从缓存获取,key为ID,缓存具体看 ehcache.xml 配置文件
public WeatherDto getById(String id) {
log.info("WeatherManager#getById: id={}", id);
try {
RestTemplate restTemplate = new RestTemplate();
WeatherDto dto = restTemplate.getForObject(SOJSON_WEATHER_URL , WeatherDto.class,id);
if(dto != null && dto.isSuccess()){
return dto;
}else{
log.error("获取天气数据返回错误:{}", dto);
}
} catch (RestClientException e) {
log.error("获取天气数据返回错误,出现异常.", e);
}
return null;
}
}
@Cacheable API 说明
使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。 如:
//从参数中获取参数名为 id 的值
@Cacheable(value="cacheName", key="#id")
//多个参数中从左到右 第一个,也就是index 为 0 。
@Cacheable(value="cacheName", key="#p0")
这里如果缓存命中则返回,如果没命中则执行方法里的内容,获取到返回值后会自动存储到缓存中,用于下一次获取。
版权所属:SO JSON在线解析
原文地址:https://www.sojson.com/blog/352.html
转载时必须以链接形式注明原始出处及本声明。
如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。