三十五、Spring Boot使用EhCache做集中式缓存

#                      Spring Boot使用EhCache做集中式缓存

##1、添加缓存依赖

在pom.xml中添加以下依赖:

<!-- 加入缓存的依赖 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId> 
    <artifactId>ehcache</artifactId> 
</dependency> 

##2、EhCache缓存配置文件

配置EhCache缓存配置文件:ehcache-config.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <!-- 缓存名称 -->
    <cache name="enterprise"  
           maxEntriesLocalHeap="200"
           timeToLiveSeconds="600">
    </cache>
</ehcache>

##3、在application.properties中声明使用的缓存类型及配置文件地址

#程序启动端口号
server.port=8082

#至于具体哪个配置文件会被加载,需要在application.prperties文件中通过spring.profiles.active属性来设置,其值对应{prodile}值
#application-{profile}.prperties文件中通过spring
#如果程序打成了jar,可以通过执行java -jar xxxx.jar --spring.profiles.active=test
spring.profiles.active=dev

#配置mysql连接   默认使用的JDBC连接数据源
spring.datasource.url=jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class=com.mysql.cj.jdbc.Driver

#打印sql语句
spring.jpa.properties.hibernate.show_sql=true

#使用缓存的类型
spring.cache.type=ehcache
#使用缓存的地址
spring.cache.ehcache.config=classpath:config/ehcache-config.xml


##4、在启动程序入口开启缓存

package com.yang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching   //开启缓存
public class DubboSpringbootOneApplication {

	public static void main(String[] args) {
		SpringApplication.run(DubboSpringbootOneApplication.class, args);
	}
}

##5、JPA实体类声明

package com.yang;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Enterprise implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue
	private Integer id;

	@Column(nullable = false)
	private String name;

	@Column(nullable = false)
	private String address;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name == null ? null : name.trim();
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address == null ? null : address.trim();
	}

	@Override
	public String toString() {
		return "Enterprise [id=" + id + ", name=" + name + ", address=" + address + "]";
	}
	
	
}

##6、JPA接口声明

package com.yang;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;




/**
 * 继承JpaRepository  接口,实现JPA
 * @author yang
 */
@CacheConfig(cacheNames="enterprise")//<!-- 声明缓存使用的缓存名称 -->
public interface EnterpriseRepo extends JpaRepository<Enterprise, Integer>,JpaSpecificationExecutor<Enterprise>{
	
	//配置这个函数的返回值加入到缓存中,查询的时候先从缓存中获取,如果不存在再去数据库中查询。
	//除了@Cacheable,还有@CachePut和@CacheEvict。
	//@CachePut它每次都会调用函数,所以主要用于数据库新增和修改上。
	//@CacheEvict 配置函数上,通常用在删除方法上,用来从缓存中移除相应数据。
	@Cacheable
	Enterprise findByid(Integer id);
	
	
  /*
   * 在spring boot中通过@EnableCaching注解自动化配置合适的缓存管理器。
   * Generic、JCache、EhCache。。。reids   
   * spring.chache.type强制指定缓存管理器。
   * 可以直接在resources下配置ehcache.xml,spring boot会自己侦测到。
   * 但是为了后期的演示,我们将其放到config文件夹中,并且改名为ehcache-config.xml,然后配置
   * 指定这个xml :spring.cache.ehchache.config=classpath:cofnig/ehcache-config.xml
   */
	@CachePut
	Enterprise save(Enterprise enterprise);
	
}

##7、测试缓存使用

package com.yang;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DubboSpringbootOneApplicationTests {

	@Autowired
	private EnterpriseRepo enterprise;
	
	@Test
	public void contextLoads() {
		Enterprise enter1=enterprise.findByid(1);
		System.out.println("enter1:"+enter1);
		Enterprise enter2=enterprise.findByid(1);
		System.out.println("enter2:"+enter2);
	}

}

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值