springboot整合Ehcache

本文详细介绍了如何在Spring Boot项目中整合Ehcache缓存,包括配置Maven依赖、启用缓存注解、配置application.properties和ehcache.xml文件,以及实现缓存测试的方法。

首先引入maven包:

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

  然后在启动类上添加注解:@EnableCaching//开启缓存

配置application.properties

#server
server.servlet.context-path=/demo
server.port=8080
server.tomcat.uri-encoding=utf-8

#设置freemarker模板后缀
spring.freemarker.suffix=.html
#修改模板默认文件夹
spring.freemarker.template-loader-path=classpath:/web

#datasource  tomcat-jdbc
spring.datasource.url=jdbc:mysql://localhost:3306/boot?characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#jpa
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

#ehcache
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:/config/ehcache.xml

  配置ehcache.xml:

       <!--  
           设定具体的命名缓存的数据过期策略。每个命名缓存代表一个缓存区域
           缓存区域(region):一个具有名称的缓存块,可以给每一个缓存块设置不同的缓存策略。
           如果没有设置任何的缓存区域,则所有被缓存的对象,都将使用默认的缓存策略。即:<defaultCache.../>
           Hibernate 在不同的缓存区域保存不同的类/集合。
            对于类而言,区域的名称是类名。如:com.atguigu.domain.Customer
            对于集合而言,区域的名称是类名加属性名。如com.atguigu.domain.Customer.orders
       -->
       <!--  
           name: 设置缓存的名字,它的取值为类的全限定名或类的集合的名字 
           maxElementsInMemory: 设置基于内存的缓存中可存放的对象最大数目 
           eternal: 设置对象是否为永久的, true表示永不过期, 此时将忽略timeToIdleSeconds 和 timeToLiveSeconds属性; 默认值是false 
                                timeToIdleSeconds:设置对象空闲最长时间,以秒为单位, 超过这个时间,对象过期。当对象过期时,EHCache会把它从缓存中清除。如果此值为0,表示对象可以无限期地处于空闲状态。 
           timeToLiveSeconds:设置对象生存最长时间,超过这个时间,对象过期。如果此值为0,表示对象可以无限期地存在于缓存中. 该属性值必须大于或等于 timeToIdleSeconds 属性值 
           overflowToDisk:设置基于内存的缓存中的对象数目达到上限后,是否把溢出的对象写到基于硬盘的缓存中 
       -->
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    <!--  
        指定一个目录:当 EHCache 把数据写到硬盘上时, 将把数据写到这个目录下.
    -->     
    <diskStore path="d:\\cache"/>

    <!--设置缓存的默认数据过期策略 -->
    <!-- <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /> -->
    
    <cache name="Student" eternal="false" maxElementsInMemory="10000" timeToIdleSeconds="200" overflowToDisk="true" timeToLiveSeconds="200"/>

</ehcache>

  这样,Ehcache已经整合到springboot中了。

简单测试缓存:

package com.example.demo.dao;


import org.springframework.data.jpa.repository.JpaRepository;

import com.example.demo.entity.Student;

public interface StudentDao extends JpaRepository<Student, Integer> {
	Student findStudentById(Integer id);
}

  

package com.example.demo.service;

import com.example.demo.entity.Student;

public interface StudentService {
	public Student getStudentById(Integer id) ;
}

  

package com.example.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.example.demo.dao.StudentDao;
import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;

@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentDao studentDao;
	
	@Cacheable(cacheNames= {"Student"})
	public Student getStudentById(Integer id) {
		return studentDao.findStudentById(id);
	}
}

  

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;

@Controller
@RequestMapping("/student/")
public class StudentController {
	@Autowired
	private StudentService studentService;
	
	@RequestMapping("index")
	public String index() {
		
		return "index";
	}
	
	@RequestMapping("show")
	public String getStudengById(Student student,Model model) {
		student = studentService.getStudentById(student.getId());
		model.addAttribute("student", student);
		return "index";
	}

}

  

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>index</h1>
<a href="/demo/student/show?id=1">查询学生</a>
<#if student??>
    用户名:${student.name}
</#if>
</body>
</html>

  第一次查询会产生SQL,第二次查询没有产生SQL,说明缓存已经失效,或者第一次查询完毕后,修改数据库数据,再次查询,数据未改变,说明是从缓存获取的数据。

转载于:https://www.cnblogs.com/blog411032/p/10371144.html

### 整合 Ehcache 到 Spring Boot 项目的指南 #### 添加必要的依赖项 为了使 Spring Boot 支持 Ehcache 缓存,`spring-boot-starter-cache` 和 `ehcache` 的 Maven/Gradle 依赖是必不可少的。前者提供了一个抽象层用于管理各种类型的缓存机制;后者作为具体的缓存解决方案被引入。 对于Maven项目而言,应在pom.xml中加入以下片段: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 而对于 Gradle 用户,则需在 build.gradle 文件内添加相应条目[^1]。 #### 配置 Application 属性文件 创建或编辑现有的application.yml (或 .properties),定义所需的缓存名称以及指向自定义配置文件的位置(如果有的话)。下面是一个简单的YAML格式的例子: ```yaml spring: cache: type: ehcache cache-names: cache1, cache2 ehcache: config: classpath:ehcache.xml ``` 这段设置指定了两个名为 "cache1" 和 "cache2" 的缓存实例,并告知应用程序去类路径下寻找名为 `ehcache.xml` 的具体配置文档。 如果没有特别指定 `spring.cache.ehcache.config` 参数,默认情况下将会尝试加载位于classpath根目录下的 `ehcache.xml` 文件来进行初始化操作[^2]。 #### 定义 Ehcache XML 配置 最后一步是在资源目录(src/main/resources/)里放置一个合适的 `ehcache.xml` 文件,它包含了关于各个缓存区域的具体参数设定,比如最大容量、过期策略等特性。这里给出一段基础模板供参考: ```xml <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <!-- 默认缓存 --> <defaultCache maxEntriesLocalHeap="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120"/> <!-- 自定义缓存区 &#39;cache1&#39; --> <cache name="cache1" maxEntriesLocalHeap="500" eternal="true"/> <!-- 另外一个自定义缓存区 &#39;cache2&#39; --> <cache name="cache2" maxEntriesLocalHeap="700" timeToIdleSeconds="300" /> </ehcache> ``` 上述XML片断展示了如何为不同的命名空间(`cache1`, `cache2`)定制化各自的存储行为和生命周期属性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值