简述
源代码
环境
IDE: IntelliJ IDEA
JDK: 1.8.0_u162
Framework: spring boot, dubbo
Cache: Redis
WebServer: Tomcat (本地端口8088)
开发
pom dependency
1 | <dependency> |
appliation.properties redis配置
通用
1 | spring.redis.database=2 |
单实例
1 | spring.redis.host=127.0.0.1 |
Sentinel集群
1 | spring.redis.sentinel.master=mymaster |
配置类
RedisCacheConfig
1 | package cn.icmyfuture.iarc.data.common; |
CacheConfig
1 | package cn.icmyfuture.iarc.data.config; |
SpringBoot开启缓存
1 | @EnableCaching |
Service实现中,使用redis缓存
由于dubbo不支持使用注解@Cacheable,只能选择以下2种解决方式之一(本文使用第一种方式,对key的设置有更大的灵活性)
- 使用@Service注解,在代码中获取/设置缓存
- 不使用@Service注解,使用dubbo配置的方式来注册服务,同时开启缓存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Autowired
private CacheManager cacheManager;
@Override
public List<User> getAllUsers() {
Cache cache = cacheManager.getCache(CacheConfig.getAllUsers);
String key = String.format("%s", CacheConfig.getAllUsers);
Cache.ValueWrapper wrapper = cache.get(key);
List<User> users;
if (wrapper == null) {
users = userDao.getAllUsers();
cache.put(key, users);
return users;
}
return (List<User>) wrapper.get();
}
调试
- 访问
http://localhost:8002/user/getAllUsers
来验证redis缓存的有效性 - 访问
http://localhost:8002/druid/index.html
来查看SQL监控
以验证sql仅被执行了一次
部署
centos下配置好redis。maven工程根目录下执行命令mvn clean install
,然后将iarc-data与iarc-service部署到tomcat中,访问http://localhost:8080/service/user/getAllUsers
参考
- windows下redis安装配置
- windows下redis集群配置
- Redis Sentinel 1 2 3 4
- spring boot使用redis