Springboot 集成 Ehcache 代码讲解

JSON 2019-12-17 23:23:34 28397

一些小微服务项目又要用到缓存,但是又不想搭建  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

转载时必须以链接形式注明原始出处及本声明。

本文主题:

如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。

关于作者
一个低调而闷骚的男人。
相关文章
Springboot HTTP Get/Post 请求讲解Springboot几行代码完成Http请求
Springboot 集成Aliyun MQ消息队列,Aliyun 消息队列配置及代码实现
Springboot + Freemarker 集成配置
SpringBoot 集成Spring-data-redis,redis对象序列化存储
Springboot 集成Freemarker 自定义标签解决方案
sojson 特效,本站页面“线条”HTML5实现讲解、特效代码下载
利用七牛镜像扒网站的源代码,操作视频讲解
百度加强推送URL链接,百度SEO强行推送链接JavaScript代码案例讲解
Springboot HTTP请求,Springboot HTTP 请求 Demo。Get/Post
Maven的Mirror和Repository 的详细讲解
最新文章
PHP变量剖析 11
SQL全外连接剖析 119
SQL自然连接剖析 147
springboot启动原理 245
SQL右连接【RIGHT JOIN】详解及图解 450
SQL左链接【LEFT JOIN】详解及图解 357
SQL非等值连接剖析 262
SQL等链接剖析 291
SQL内连接详解及图解 385
python之numpy常用的100种数值相关方法及代码示例 231
最热文章
最新MyEclipse8.5注册码,有效期到2020年 (已经更新) 679241
苹果电脑Mac怎么恢复出厂系统?苹果系统怎么重装系统? 674561
免费天气API,全国天气 JSON API接口,可以获取五天的天气预报 599031
免费天气API,天气JSON API,不限次数获取十五天的天气预报 565278
Jackson 时间格式化,时间注解 @JsonFormat 用法、时差问题说明 551715
我为什么要选择RabbitMQ ,RabbitMQ简介,各种MQ选型对比 509186
Elasticsearch教程(四) elasticsearch head 插件安装和使用 479645
Jackson 美化输出JSON,优雅的输出JSON数据,格式化输出JSON数据... ... 262820
Java 信任所有SSL证书,HTTPS请求抛错,忽略证书请求完美解决 244092
Elasticsearch教程(一),全程直播(小白级别) 225127
支付扫码

所有赞助/开支都讲公开明细,用于网站维护:赞助名单查看

查看我的收藏

正在加载... ...