目录
  1. 1. 集成说明
  2. 2. 集成步骤
  3. 3. 使用方法
springboot集成redis、ehcache

集成说明

可根据属性配置缓存到redis和ehcache

集成步骤

1、pom.xml文件引入依赖包

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

2、application.yml配置ehcache和redis属性值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
spring:
# 缓存配置
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
redis:
host: 127.0.0.1
password: 123456
# 连接超时时间(毫秒),启动时会加载大量缓存,将缓存时间增加为1分钟
timeout: 1000
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
database: 0
lettuce:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认 8
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
max-wait: -1
# 连接池中的最大空闲连接 默认 8
max-idle: 8
# 连接池中的最小空闲连接 默认 0
min-idle: 0

3、创建ehcache配置文件:ehcache.xml

1
2
3
4
5
6
7
8
9
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<defaultCache maxElementsInMemory="10000"
overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="3600"
timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LRU"/>
<cache name="kbs" maxEntriesLocalHeap="100" eternal="false" timeToIdleSeconds="3600"
timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LRU" />
</ehcache>

4、创建缓存配置类CacheConfig,注入redis和ehcache管理器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class CacheConfig {

private final CacheProperties cacheProperties;

@Autowired
private ObjectMapper objectMapper;

public interface CacheManagerNames {
String REDIS_CACHE_MANAGER = "redisCacheManager";
String EHCACHE_CACHE_MANAGER = "ehCacheManager";
}

CacheConfig(CacheProperties cacheProperties) {
this.cacheProperties = cacheProperties;
}

@Bean
public RedisTemplate<String, Object> RedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}

/**
* @Author yuxk
* @Description 设置redis管理器
* @Date 2020/9/18 13:59
* @Param factory
* @Return org.springframework.data.redis.cache.RedisCacheManager
**/
@Primary
@Bean(name = CacheManagerNames.REDIS_CACHE_MANAGER)
public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// 解决查询缓存转换异常的问题
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 配置序列化(解决乱码的问题),过期时间30秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}

/**
* @Author yuxk
* @Description 设置ehcache管理器
* @Date 2020/9/18 14:00
* @Param
* @Return org.springframework.cache.ehcache.EhCacheCacheManager
**/
@Bean(name = CacheManagerNames.EHCACHE_CACHE_MANAGER)
public EhCacheCacheManager ehCacheCacheManager() {
Resource location = cacheProperties.resolveConfigLocation(cacheProperties.getEhcache().getConfig());
return new EhCacheCacheManager(EhCacheManagerUtils.buildCacheManager(location));
}

}

5、若需要手动添加ehcache缓存,可新增工具类EhCacheUtils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.powersi.kbs.config;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Configuration;

/**
* @ClassName EhCacheUtils
* @Description ehcache工具类
* @Author yuxk
* @Date 2020/9/17 13:37
* @Version 3.0
**/
@Configuration
public class EhCacheUtils {

private static EhCacheCacheManager ehCacheCacheManager;

/**
* @Author yuxk
* @Description 设置缓存管理器
* @Date 2020/9/17 17:22
* @Param manager 缓存管理器
* @Return void
**/
@Autowired
public void setManager(EhCacheCacheManager manager) {
EhCacheUtils.ehCacheCacheManager = manager;
}

/**
* @Author yuxk
* @Description 获取缓存
* @Date 2020/9/17 17:18
* @Param cacheName 缓存名称
* @Param key 缓存键
* @Return java.lang.Object
**/
public static Object get(String cacheName, String key) {
Element element = cache(cacheName).get(key);
return element == null ? null : element.getObjectValue();
}

/**
* @Author yuxk
* @Description 放入缓存, 并设置过期时间
* @Date 2020/9/17 17:19
* @Param cacheName 缓存名称
* @Param key 缓存键
* @Param value 缓存值
* @Param ttl
* @Param tti
* @Return void
**/
public static void put(String cacheName, String key, Object value, Integer ttl) {
Element e = new Element(key, value);
//不设置则使用xml配置
if (ttl != null) {
e.setTimeToLive(ttl);
}
cache(cacheName).put(e);
}

/**
* @Author yuxk
* @Description 加入到缓存, 过期时间与xml配置有关
* @Date 2020/9/17 17:24
* @Param cacheName 缓存名称
* @Param key 缓存键
* @Param value 缓存值
* @Return void
**/
public static void put(String cacheName, String key, Object value) {
put(cacheName, key, value, null);
}

/**
* @Author yuxk
* @Description 根据缓存名称和缓存键移除缓存
* @Date 2020/9/17 17:20
* @Param cacheName 缓存名称
* @Param key 缓存键
* @Return boolean
**/
public static boolean remove(String cacheName, Object key) {
return cache(cacheName).remove(key);
}

/**
* @Author yuxk
* @Description 根据缓存名称移除所有缓存
* @Date 2020/9/17 17:21
* @Param cacheName
* @Return void
**/
public static void removeAll(String cacheName) {
cache(cacheName).removeAll();
}

/**
* @Author yuxk
* @Description 获取缓存对象
* @Date 2020/9/17 17:22
* @Param cacheName 缓存名称
* @Return net.sf.ehcache.Cache
**/
private static Cache cache(String cacheName) {
CacheManager cacheManager = ehCacheCacheManager.getCacheManager();
if (!cacheManager.cacheExists(cacheName)) {
cacheManager.addCache(cacheName);
}
return cacheManager.getCache(cacheName);
}

}

使用方法

使用示例

1
2
3
4
5
6
7
public static final String USER_CACHE = "userList";

@Cacheable(cacheNames = "user", key = "#root.target.USER_CACHE",
cacheManager = CacheConfig.CacheManagerNames.EHCACHE_CACHE_MANAGER, unless = "#result==null")
public List<User> listUsers() {
return userDao.listUsers();
}

Cacheable属性解释
cacheNames:缓存名称
key:缓存键
cacheManager:缓存管理器,支持ehcache和redis,若不添加该属性默认缓存到redis,可选参数:CacheConfig.CacheManagerNames.EHCACHE_CACHE_MANAGER、CacheConfig.CacheManagerNames.REDIS_CACHE_MANAGER
unless:条件判断,代码给出的条件是结果不为null才加入到缓存

文章作者: 微光
文章链接: http://www.guduke.cn/2020/11/29/redis-ehcache/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 微光
打赏
  • 微信
  • 支付宝

评论