当前位置:网站首页>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
边栏推荐
猜你喜欢

MySQL index and data storage structure foundation

Difference between bow and cbow

Flume learning III
![[new book recommendation] mongodb performance tuning](/img/2c/e5a814df4412a246c703ca548a4f68.png)
[new book recommendation] mongodb performance tuning
![[Ubuntu redis installation]](/img/66/d8054ae89007180b317641cf92d1cc.png)
[Ubuntu redis installation]

Shenhe thermomagnetic: Super fusion dual active cluster solution for MES system

Flume learning 4

Notes on masking and padding in tensorflow keras

7.手机登陆功能开发

The present situation and challenge of the infrastructure of Yiwen parsing database
随机推荐
【JVM】G1垃圾回收器簡述
Use and description of event delegation
ABAP-时间函数
Redis docker 主从模式与哨兵sentinel
JVM memory common parameter configuration set
MySQL optimization
Cloud native database
Description of event object
机械臂速成小指南(四):机械臂关键部件之减速机
JUL简介
About Jul
Task summary in NLP
1, 基本配置
Flume learning III
【新书推荐】Cleaning Data for Effective Data Science
机械臂速成小指南(五):末端执行器
Installing Oracle database process in windows2007 on VM
Follow the wechat oauth2.0 access scheme
【ARK UI】HarmonyOS ETS的启动页的实现
正则表达式基础