refactor: 移除 Ehcache,默认缓存设置为 Redis

This commit is contained in:
xiongxiaoyang 2023-04-14 10:40:54 +08:00
parent 282bc7b707
commit 29d074ec18
11 changed files with 56 additions and 288 deletions

View File

@ -200,10 +200,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<!--war包部署需要-->
<!--<dependency>-->

View File

@ -5,11 +5,8 @@ import com.java2nb.common.redis.shiro.RedisCacheManager;
import com.java2nb.common.redis.shiro.RedisManager;
import com.java2nb.common.redis.shiro.RedisSessionDAO;
import com.java2nb.system.shiro.UserRealm;
import net.sf.ehcache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
@ -29,6 +26,7 @@ import java.util.LinkedHashMap;
*/
@Configuration
public class ShiroConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
@ -38,9 +36,6 @@ public class ShiroConfig {
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.cache.type}")
private String cacheType ;
@Value("${server.session-timeout}")
private int tomcatTimeout;
@ -67,8 +62,8 @@ public class ShiroConfig {
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/login","anon");
filterChainDefinitionMap.put("/getVerify","anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/getVerify", "anon");
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
@ -92,11 +87,7 @@ public class ShiroConfig {
//设置realm.
securityManager.setRealm(userRealm());
// 自定义缓存实现 使用redis
if (Constant.CACHE_TYPE_REDIS.equals(cacheType)) {
securityManager.setCacheManager(rediscacheManager());
} else {
securityManager.setCacheManager(ehCacheManager());
}
securityManager.setCacheManager(rediscacheManager());
securityManager.setSessionManager(sessionManager());
return securityManager;
}
@ -108,8 +99,7 @@ public class ShiroConfig {
}
/**
* 开启shiro aop注解支持.
* 使用代理方式;所以需要开启代码支持;
* 开启shiro aop注解支持. 使用代理方式;所以需要开启代码支持;
*
* @param securityManager
* @return
@ -138,8 +128,7 @@ public class ShiroConfig {
}
/**
* cacheManager 缓存 redis实现
* 使用的是shiro-redis开源插件
* cacheManager 缓存 redis实现 使用的是shiro-redis开源插件
*
* @return
*/
@ -151,8 +140,7 @@ public class ShiroConfig {
/**
* RedisSessionDAO shiro sessionDao层的实现 通过redis
* 使用的是shiro-redis开源插件
* RedisSessionDAO shiro sessionDao层的实现 通过redis 使用的是shiro-redis开源插件
*/
@Bean
public RedisSessionDAO redisSessionDAO() {
@ -163,11 +151,7 @@ public class ShiroConfig {
@Bean
public SessionDAO sessionDAO() {
if (Constant.CACHE_TYPE_REDIS.equals(cacheType)) {
return redisSessionDAO();
} else {
return new MemorySessionDAO();
}
return redisSessionDAO();
}
/**
@ -184,19 +168,4 @@ public class ShiroConfig {
return sessionManager;
}
@Bean
public EhCacheManager ehCacheManager() {
EhCacheManager em = new EhCacheManager();
em.setCacheManager(cacheManager());
return em;
}
@Bean("cacheManager2")
CacheManager cacheManager(){
return CacheManager.create();
}
}

View File

@ -39,7 +39,7 @@ spring:
redis:
host: 127.0.0.1
port: 6379
password: test
password: test123456
# 连接超时时间毫秒
timeout: 10000
jedis:

View File

@ -1,8 +1,8 @@
server:
session-timeout: 18000
# tomcat:
# max-threads: 1000
# min-spare-threads: 30
# tomcat:
# max-threads: 1000
# min-spare-threads: 30
port: 80
# uri-encoding: utf-8
#security:
@ -15,7 +15,7 @@ spring:
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
profiles:
profiles:
active: dev
servlet:
multipart:
@ -24,10 +24,7 @@ spring:
devtools:
restart:
enabled: true
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
mybatis:
configuration:
#自动将数据库带下划线的表字段值映射到Java类的驼峰字段上

View File

@ -32,12 +32,6 @@
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--ehcache-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<!--集成redis-->
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -1,122 +0,0 @@
package com.java2nb.novel.core.cache.impl;
import com.java2nb.novel.core.cache.CacheService;
import lombok.RequiredArgsConstructor;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
/**
* @author xxy
*/
@ConditionalOnProperty(prefix = "cache", name = "type", havingValue = "ehcache")
@RequiredArgsConstructor
@Service
public class EhCacheServiceImpl implements CacheService {
private final CacheManager cacheManager;
/**
* 获得一个Cache没有则创建一个
*
* @return
*/
private Cache getCache() {
Cache cache = cacheManager.getCache("util_cache");
return cache;
}
@Override
public String get(String key) {
Element element = getCache().get(key);
return element == null ? null : (String) element.getObjectValue();
}
@Override
public void set(String key, String value) {
Element element = new Element(key, value);
Cache cache = getCache();
//不过期
cache.getCacheConfiguration().setEternal(true);
cache.put(element);
}
@Override
public void set(String key, String value, long timeout) {
Element element = new Element(key, value);
element.setTimeToLive((int) timeout);
Cache cache = getCache();
cache.put(element);
}
@Override
public void del(String key) {
getCache().remove(key);
}
@Override
public boolean contains(String key) {
return getCache().isKeyInCache(key);
}
@Override
public void expire(String key, long timeout) {
Element element = getCache().get(key);
if (element != null) {
Object value = element.getValue();
element = new Element(key, value);
element.setTimeToLive((int) timeout);
Cache cache = getCache();
cache.put(element);
}
}
/**
* 根据key获取缓存的Object类型数据
*/
@Override
public Object getObject(String key) {
Element element = getCache().get(key);
return element == null ? null : element.getObjectValue();
}
/**
* 设置Object类型的缓存
*/
@Override
public void setObject(String key, Object value) {
Element element = new Element(key, value);
Cache cache = getCache();
//不过期
cache.getCacheConfiguration().setEternal(true);
cache.put(element);
}
/**
* 设置一个有过期时间的Object类型的缓存,单位秒
*/
@Override
public void setObject(String key, Object value, long timeout) {
Element element = new Element(key, value);
element.setTimeToLive((int) timeout);
Cache cache = getCache();
cache.put(element);
}
}

View File

@ -2,7 +2,6 @@ package com.java2nb.novel.core.cache.impl;
import com.java2nb.novel.core.cache.CacheService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@ -12,62 +11,61 @@ import java.util.concurrent.TimeUnit;
/**
* @author xxy
*/
@ConditionalOnProperty(prefix = "cache", name = "type", havingValue = "redis")
@RequiredArgsConstructor
@Service
public class RedisServiceImpl implements CacheService {
private final StringRedisTemplate stringRedisTemplate;
private final StringRedisTemplate stringRedisTemplate;
private final RedisTemplate<Object, Object> redisTemplate;
private final RedisTemplate<Object, Object> redisTemplate;
@Override
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@Override
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@Override
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key,value);
}
@Override
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
@Override
public void set(String key, String value, long timeout) {
stringRedisTemplate.opsForValue().set(key,value,timeout, TimeUnit.SECONDS);
@Override
public void set(String key, String value, long timeout) {
stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
}
@Override
public Object getObject(String key) {
return redisTemplate.opsForValue().get(key);
}
@Override
public Object getObject(String key) {
return redisTemplate.opsForValue().get(key);
}
@Override
public void setObject(String key, Object value) {
redisTemplate.opsForValue().set(key,value);
}
@Override
public void setObject(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
@Override
public void setObject(String key, Object value, long timeout) {
redisTemplate.opsForValue().set(key,value,timeout, TimeUnit.SECONDS);
}
@Override
public void setObject(String key, Object value, long timeout) {
redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
@Override
public void del(String key) {
redisTemplate.delete(key);
stringRedisTemplate.delete(key);
}
@Override
public void del(String key) {
redisTemplate.delete(key);
stringRedisTemplate.delete(key);
}
@Override
public boolean contains(String key) {
return redisTemplate.hasKey(key) || stringRedisTemplate.hasKey(key);
}
@Override
public boolean contains(String key) {
return redisTemplate.hasKey(key) || stringRedisTemplate.hasKey(key);
}
@Override
public void expire(String key, long timeout) {
redisTemplate.expire(key,timeout, TimeUnit.SECONDS);
stringRedisTemplate.expire(key,timeout, TimeUnit.SECONDS);
}
@Override
public void expire(String key, long timeout) {
redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
}

View File

@ -9,7 +9,7 @@ spring:
#Redis服务器连接端口
port: 6379
#Redis服务器连接密码
password: test
password: test123456
jedis:
pool:
#连接池最大连接数使用负值表示没有限制

View File

@ -6,7 +6,7 @@ spring:
mode: LEGACYHTML5 #去除thymeleaf的html严格校验thymeleaf.mode=LEGACYHTML5
cache: false # 是否开启模板缓存默认true,建议在开发时关闭缓存,不然没法看到实时
# 将所有数字转为 String 类型返回避免前端数据精度丢失的问题
# 将所有数字转为 String 类型返回避免前端数据精度丢失的问题
jackson:
generator:
write-numbers-as-strings: true
@ -16,10 +16,6 @@ spring:
multipart:
max-file-size: 1048576
#缓存类型ehcache(默认)redis
cache:
type: ehcache
mybatis:
configuration:
#自动将数据库带下划线的表字段值映射到Java类的驼峰字段上

View File

@ -1,30 +0,0 @@
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<!--timeToIdleSeconds 当缓存闲置n秒后销毁 -->
<!--timeToLiveSeconds 当缓存存活n秒后销毁 -->
<!-- 缓存配置 name:缓存名称 maxElementsInMemory缓存最大个数 eternal:对象是否永久有效一但设置了timeout将不起作用
timeToIdleSeconds设置对象在失效前的允许闲置时间单位仅当eternal=false对象不是永久有效时使用可选属性默认值是0也就是可闲置时间无穷大
timeToLiveSeconds设置对象在失效前允许存活时间单位最大时间介于创建时间和失效时间之间仅当eternal=false对象不是永久有效时使用默认是0.也就是对象存活时间无穷大
overflowToDisk当内存中对象数量达到maxElementsInMemory时Ehcache将会对象写到磁盘中 diskSpoolBufferSizeMB这个参数设置DiskStore磁盘缓存的缓存区大小默认是30MB每个Cache都应该有自己的一个缓冲区
maxElementsOnDisk硬盘最大缓存个数 diskPersistent是否缓存虚拟机重启期数据 Whether the disk
store persists between restarts of the Virtual Machine. The default value
is false. diskExpiryThreadIntervalSeconds磁盘失效线程运行时间间隔默认是120秒 memoryStoreEvictionPolicy当达到maxElementsInMemory限制时Ehcache将会根据指定的策略去清理内存默认策略是
LRU最近最少使用你可以设置为FIFO先进先出或是LFU较少使用 clearOnFlush内存数量最大时是否清除 maxEntriesLocalHeap="1000"
: 堆内存中最大缓存对象数,0没有限制(必须设置) maxEntriesLocalDisk="1000" : 硬盘最大缓存个数 -->
<!-- 磁盘缓存位置 -->
<diskStore path="user.dir/cachedata" />
<!-- 默认缓存 -->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120"
maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="util_cache" maxEntriesLocalHeap="0" eternal="true"
overflowToDisk="true" diskPersistent="true" />
</ehcache>

View File

@ -1,30 +0,0 @@
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<!--timeToIdleSeconds 当缓存闲置n秒后销毁 -->
<!--timeToLiveSeconds 当缓存存活n秒后销毁 -->
<!-- 缓存配置 name:缓存名称 maxElementsInMemory缓存最大个数 eternal:对象是否永久有效一但设置了timeout将不起作用
timeToIdleSeconds设置对象在失效前的允许闲置时间单位仅当eternal=false对象不是永久有效时使用可选属性默认值是0也就是可闲置时间无穷大
timeToLiveSeconds设置对象在失效前允许存活时间单位最大时间介于创建时间和失效时间之间仅当eternal=false对象不是永久有效时使用默认是0.也就是对象存活时间无穷大
overflowToDisk当内存中对象数量达到maxElementsInMemory时Ehcache将会对象写到磁盘中 diskSpoolBufferSizeMB这个参数设置DiskStore磁盘缓存的缓存区大小默认是30MB每个Cache都应该有自己的一个缓冲区
maxElementsOnDisk硬盘最大缓存个数 diskPersistent是否缓存虚拟机重启期数据 Whether the disk
store persists between restarts of the Virtual Machine. The default value
is false. diskExpiryThreadIntervalSeconds磁盘失效线程运行时间间隔默认是120秒 memoryStoreEvictionPolicy当达到maxElementsInMemory限制时Ehcache将会根据指定的策略去清理内存默认策略是
LRU最近最少使用你可以设置为FIFO先进先出或是LFU较少使用 clearOnFlush内存数量最大时是否清除 maxEntriesLocalHeap="1000"
: 堆内存中最大缓存对象数,0没有限制(必须设置) maxEntriesLocalDisk="1000" : 硬盘最大缓存个数 -->
<!-- 磁盘缓存位置 -->
<diskStore path="user.dir/cachedata" />
<!-- 默认缓存 -->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120"
maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="util_cache" maxEntriesLocalHeap="0" eternal="true"
overflowToDisk="true" diskPersistent="true" />
</ehcache>