JAVA全系列 教程
3762个小节阅读:7089.7k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在广告服务模块添加redis起步依赖
xxxxxxxxxx
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在配置中心中配置redis连接
xxxxxxxxxx
spring:
# redis
data:
redis:
host: 192.168.0.99
port: 6379
timeout: 30000
jedis:
pool:
max-idle: 8
max-wait: -1
max-active: 8
min-idle: 0
修改广告服务实现类
@DubboService
public class CategoryServiceImpl implements CategoryService {
@Autowired
private CategoryMapper categoryMapper;
// 对象名必须叫redisTemplate,否则由于容器中有多个RedisTemplate对象造成无法注入
@Autowired
private RedisTemplate redisTemplate;
@Override
public void add(Category category) {
categoryMapper.insert(category);
refreshRedisCategory();
}
@Override
public void update(Category category) {
categoryMapper.updateById(category);
refreshRedisCategory();
}
@Override
public void updateStatus(Long id, Integer status) {
Category category = categoryMapper.selectById(id);
category.setStatus(status);
categoryMapper.updateById(category);
refreshRedisCategory();
}
@Override
public void delete(Long[] ids) {
categoryMapper.deleteBatchIds(Arrays.asList(ids));
}
@Override
public Category findById(Long id) {
return categoryMapper.selectById(id);
}
@Override
public Page<Category> search(int page, int size) {
return categoryMapper.selectPage(new Page(page,size),null);
}
@Override
public List<Category> findAll() {
// 1.从redis中查询启用的广告
// 1.1 获取操作redis中list数据的对象
ListOperations<String,Category> listOperations = redisTemplate.opsForList();
// 1.2 从redis中获取所有启用的广告
List<Category> categoryList = listOperations.range("categories", 0, -1);
if (categoryList != null && categoryList.size() > 0){
// 2.如果查到结果,直接返回
System.out.println("从redis中查询广告");
return categoryList;
}else{
// 3.如果redis中没有数据,则从数据库查询广告,并同步到redis中
System.out.println("从mysql中查询广告");
// 从数据库查询广告
QueryWrapper<Category> queryWrapper = new QueryWrapper();
queryWrapper.eq("status",1);
List<Category> categories = categoryMapper.selectList(queryWrapper);
// 同步到redis中
listOperations.leftPushAll("categories",categories);
return categories;
}
}
/**
* 更新redis中的广告数据
*/
public void refreshRedisCategory(){
// 从数据库查询广告
QueryWrapper<Category> queryWrapper = new QueryWrapper();
queryWrapper.eq("status",1);
List<Category> categories = categoryMapper.selectList(queryWrapper);
// 删除redis中的原有广告数据
redisTemplate.delete("categories");
// 将新的广告数据同步到redis中
ListOperations<String,Category> listOperations = redisTemplate.opsForList();
listOperations.leftPushAll("categories",categories);
}
}