当前位置:网站首页>9. cache optimization
9. cache optimization
2022-06-30 09:58:00 【xjhqre】
List of articles
Cache optimization
1、 Environment building
1.1、 Import maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
1.2、 To configure redis
my redis Put it directly in windows On , therefore host For local address . See this blog for installation methods :https://www.redis.com.cn/redis-installation.html

1.3、redis Configuration class
stay config Create under directory RedisConfig class ,
It is not recommended here to value Also set to StringRedisSerializer, If I set it to StringRedisSerializer, Backward redis A conversion exception occurs when a collection is stored in .
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
// default Key The serializer is :JdkSerializationRedisSerializer
redisTemplate.setKeySerializer(new StringRedisSerializer()); // key serialize
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
1.4、 push
Submit and push to github, Signature :redis Environment configuration . Note that the branch is v1.0
2、 Cache SMS verification code
2.1、 Realize the idea
- On the server UserController In the injection RedisTemplate object , Used to operate Redis
- On the server UserController Of sendMsg In the method , Cache the randomly generated verification code to Redis in , And set the validity period as 5 minute
- On the server UserController Of login In the method , from Redis Get the cached verification code , If the login is successful, delete Redis Verification code in
2.2、 modify UserController
2.2.1、 modify sendMsg Method

2.2.2、 modify login Method

2.3、 test
To install a redis Visual interface for testing , I'm using Another Redis Desktop Manager
2.4、 Push code
Submit and push code , Signature : Cache SMS verification code .
3、 Cache dishes
3.1、 Realize the idea
- reform DishController Of list Method , First from Redis Get dish data from , Direct return if any , No need to query the database ; If not, query the database , And put the queried dish data into Redis.
- reform DishController Of save and update Method , Add the logic to clean up the cache
3.2、 modify DishController
3.2.1、 modify list Method
/** * Query the corresponding dish data according to the conditions * * @param dish * @return */
@GetMapping("/list")
public R<List<DishDto>> list(Dish dish) {
List<DishDto> dishDtoList = null;
String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
// First from redis get data
dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
if (dishDtoList != null) {
// If redis If there is data in, it will be returned directly
return R.success(dishDtoList);
}
// Construct query conditions
LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
// The query status is 1 The dishes
queryWrapper.eq(Dish::getStatus, 1);
// Add sorting criteria
queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
List<Dish> list = dishService.list(queryWrapper);
dishDtoList = list.stream().map(item -> {
DishDto dishDto = new DishDto();
// Copy properties
BeanUtils.copyProperties(item, dishDto);
// Set up DishDto Category name attribute
Long categoryId = item.getCategoryId();
Category category = categoryService.getById(categoryId);
if (category != null) {
String categoryName = category.getName();
dishDto.setCategoryName(categoryName);
}
// Set the dish taste
Long dishId = item.getId();
LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
// SQL: select * from dish_flavor where dish_id = ?
List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
dishDto.setFlavors(dishFlavorList);
return dishDto;
}).collect(Collectors.toList());
// Store data redis
redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
return R.success(dishDtoList);
}
3.2.2、 modify update Method
/** * Modify the dishes * @param dishDto * @return */
@PutMapping
public R<String> update(@RequestBody DishDto dishDto) {
log.info(dishDto.toString());
dishService.updateWithFlavor(dishDto);
// Clear the cache data of all dishes
// Set keys = redisTemplate.keys("dish_*");
// redisTemplate.delete(keys);
// Clear the cache data of dishes under a category
String key = "dish_" + dishDto.getCategoryId() + "_1";
redisTemplate.delete(key);
return R.success(" Dishes modified successfully ");
}
3.2.3、 modify save Method
/** * New dishes * @param dishDto * @return */
@PostMapping
public R<String> save(@RequestBody DishDto dishDto) {
log.info(dishDto.toString());
dishService.saveWithFlavor(dishDto);
// Clear the cache data of all dishes
// Set keys = redisTemplate.keys("dish_*");
// redisTemplate.delete(keys);
// Clear the cache data of dishes under a category
String key = "dish_" + dishDto.getCategoryId() + "_1";
redisTemplate.delete(key);
return R.success(" Added dishes successfully ");
}
3.2.4、 modify delete Method
/** * Logical deletion * @param ids * @return */
@DeleteMapping
@Transactional
public R<String> delete(Long[] ids) {
log.info(" Batch deleted id:{}", Arrays.toString(ids));
// First, delete the taste information corresponding to the dishes
dishFlavorService.removeByDishIds(Arrays.asList(ids));
// Delete the dishes logically
dishService.removeByIds(Arrays.asList(ids));
// Clear the cache data of all dishes
// Set keys = redisTemplate.keys("dish_*");
// redisTemplate.delete(keys);
// according to dishId Set query categoryId aggregate
List<Dish> dishes = dishService.listByIds(Arrays.asList(ids)); // Query all id stay ids Inside dish Record
Set<Long> categoryIds = dishes.stream().map(Dish::getCategoryId).collect(Collectors.toSet());// Take out the fields category_id aggregate ,set Collections prevent duplication
// Clear all id stay categoryIds Cache in
categoryIds.forEach(item -> {
String key = "dish_" + item + "_1";
redisTemplate.delete(key);
});
return R.success(" Delete dishes successfully ");
}
3.2.5、 Test the cache effect
3.2.6、 Push code
Submit and push code , Signature : Cache dishes . Branch :v1.0
4、 Merge code
take v1.0 The branch code is merged into the main branch
- Switch back to main branch
- Click again v1.0 Merge button for branches
- After merging, switch back to v1.0 The branch continues to develop
5、SpringCache Cache package data
5.1、 Realize the idea
- Import Spring Cache and Redis relevant maven coordinate
- stay application.yml Configure the expiration time of cached data in
- Add on startup class @EnableCaching annotation , Enable the cache annotation function
- stay SetmealController Of list Add... To the method @Cacheable annotation
- stay SetmealController Of save and delete Add... To the method CacheEvict annotation
5.2、 Import maven
We've imported redis Related dependence of , Now just import spring cache:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
5.3、 Enable caching
Mark... On the startup class @EnableCaching annotation
5.4、 Return type R Implement serialization
public class R<T> implements Serializable
5.5、 Cache package information
1、 modify SetmealController Inside list Method
/** * According to the classification id And status query package * @param setmeal * @return */
@GetMapping("/list")
@Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
public R<List<Setmeal>> list(Setmeal setmeal) {
LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
queryWrapper.orderByDesc(Setmeal::getUpdateTime);
List<Setmeal> list = setmealService.list(queryWrapper);
return R.success(list);
}
2、 to SetmealController Under the delete、save、update Methods are marked with the following comments
@CacheEvict(value = "setmealCache", allEntries = true)
5.6、 Test cache
Click package query after logging in the mobile interface , See the effect
5.7、 Push code & Merge
Submit and push code , Signature :spring cache Cache package data . Branch :v1.0
Merge steps :
- Switch to master Branch
- Click on v1.0 Click the merge button of the branch to merge
边栏推荐
- 机械臂速成小指南(四):机械臂关键部件之减速机
- 7.手机登陆功能开发
- utils session&rpc
- Description of event object
- Description of event flow
- Force buckle 428 Serialize and deserialize n-tree DFS
- Hospital integration platform super fusion infrastructure transformation scheme
- 3. integrate eslint and prettier
- MySQL index optimization miscellaneous
- Valuenotifier and valuelistenablebuilder in fluent
猜你喜欢

Abstract classes and interfaces

Follow the wechat oauth2.0 access scheme

安装和使用

G 代码解释|最重要的 G 代码命令列表

Forrester senior analyst: five important trends in the development of the hyper convergence market

无人机项目跟踪记录八十三---pcb图完成

Object detection yolov5 open source project debugging

【JVM】G1垃圾回收器簡述

云技能提升好伙伴,亚马逊云师兄今天正式营业

Bloom filter
随机推荐
Network based BGP
log4j
prometheus 监控之 ntp_exporter
How to build a private cloud and create a hybrid cloud ecosystem?
[new book recommendation] mongodb performance tuning
Flume learning III
Forrester senior analyst: five important trends in the development of the hyper convergence market
Hospital integration platform super fusion infrastructure transformation scheme
直播带货源码开发中,如何降低直播中的延迟?
Difference between bow and cbow
How to reduce the delay in live broadcast in the development of live broadcast source code with goods?
oracle跨数据库复制数据表-dblink
C语言实现扫雷游戏,附详解及完整代码
[Ubuntu redis installation]
Flutter 中的 ValueNotifier 和 ValueListenableBuilder
MySQL index and data storage structure foundation
G 代码解释|最重要的 G 代码命令列表
Comparison problems encountered in recent study
Flutter的特别之处在哪里
Description of event object