为了增添后台应用系统的吞吐量,需要为spring boot项目添加缓存模块,这里选择ehcache缓存框架为例,来具体实践介绍spring boot如何整合ehcache内存缓存框架
打开intellij idea软件,建立spring boot项目,添加maven依靠,代码如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.5</version>
</dependency>
添加@EnableCaching注解,注入自界说KeyGenerator,代码如下
@Bean
public KeyGenerator keyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
if (obj!=null){
sb.append(obj.toString());
}
}
return sb.toString();
}
};
}
在resources目次下添加ehcache.xml设置装备摆设文件,spring boot会默认读取类根路径下ehcache.xml设置装备摆设文件,添加了一个名为users的缓存空间,代码如下
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="users"
eternal="false"
maxElementsInMemory="100"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
添加一个User实体类,用于缓存测试,代码如下
public class User implements Serializable {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
添加一个UserService接口,并生当作实现类,代码如下
/**
* Created by zuli on 2018/10/9.
*/
@Service
public class UserServiceImpl implements UserService {
@Override
@Cacheable(cacheNames = {"users"},keyGenerator = "keyGenerator")
public User findByName(String name) {
System.out.println("UserServiceImpl findByName()执行,name="+name);
if ("1".equals(name)){
return new User("1","zuli");
}else if ("2".equals(name)){
return new User("2","zuli1");
}
return null;
}
}
执行SpringBootEhcacheApplication的main方式,测试缓存是否生效,代码如下
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(SpringBootEhcacheApplication.class, args);
UserService userService = context.getBean(UserService.class);
User user1 = userService.findByName("1");
System.out.println(user1);
User user11 = userService.findByName("1");
System.out.println(user11);
User user2 = userService.findByName("2");
System.out.println(user2);
User user22 = userService.findByName("2");
System.out.println(user22);
}
打印日记信息,展示出ehcache缓存生效,spring boot整合当作功,截图如下图所示
0 篇文章
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!