当前位置:网站首页>33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)
33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)
2022-07-05 17:16:00 【Small withered forest】
explain :
(1) Statement : The differences and similarities , Be clear ;
● stay 【32: The third chapter : Developing a pass service :15: Browser storage media , brief introduction ;】 in , Front end use 【 hold “ Basic information of users ” Deposit in Session Storage in 】 To reduce the pressure on the back-end interface ;;;; This is a , From the front end , To reduce the pressure on the back-end interface ;
● This blog , Use Redis Cache user information , It's using Redis To reduce the pressure of accessing the database ;
● The content of these two blogs , Its purpose is similar , It's all about reducing system pressure , Increase concurrency ;;;; however , There are differences in the focus and specific practices ;
(2) before 【Spring Boot E-commerce projects 31: Commodity classification module 10 : utilize Redis Cache accelerated response ;】、【 additional :【Spring Boot cache 】【Redis】;】 Introduced the use of Redis The case of caching ; Although there are technical differences with this blog , But the purpose is similar ; It feels like all roads lead to Rome ;
Catalog
zero : Rationality of this blog ;
2. Use redis Cache user information , Reduce database pressure : brief introduction ;
One : Use redis Cache user information , To reduce the pressure on the database ;
step1: First time registration / The logged in user ;
step2: To update / Improve user information ;
A front-end 、 Unresolved issues ;
step3:Redis Cache effect demonstration ;
zero : Rationality of this blog ;
1. Explain the problem ;
(1) We are 【32: The third chapter : Developing a pass service :15: Browser storage media , brief introduction ;】 in , Browser storage media has been introduced , Among them, it is aimed at 【 Get basic user information , Interface 】, Used in the front end Session Storage This storage medium ;;; The logic at that time was :
● The front end wants to get for the first time “ Basic information of users ” When , It will call the backend 【 Get basic user information , Interface 】 Interface ;
● meanwhile , We wrote the corresponding code in the front-end code , Take what you get “ Basic information of users ” It's stored in Session Storage in ;
● Back , The front end wants to get... For the second time “ Basic information of users ” When , It will not call the backend 【 Get basic user information , Interface 】 The interface , But from Session Storage In order to get ;
(2) Above, our angle at the front , Take advantage of Session Storage The means of , To reduce the pressure of the interface ; It improves the anti concurrency ability of the system ;(3) meanwhile , We can also start from the perspective of the back end ;;; utilize Redis Cache user information data , To reduce the pressure on the database , So as to improve the anti concurrency ability of the system ;
(4)PS: Use Session Storage A problem in storing basic user information : When the user first requests , Data exists Session Storage in ;;; But if the user changes the information , At this time, due to Session Storage, Then when users get information again , What we get is some outdated data :PS: Although I don't know much about the front-end code , But after actual measurement , Every time we update information , The front end will be removed in Session Storage Stored old user information ;
2. Use redis Cache user information , Reduce database pressure : brief introduction ;
(1) Original , Every time we need to call 【 Get user account information , Interface 】 and 【 Get basic user information , Interface 】 When , All need to access the database ;;; however , If we cache the complete user information to Redis in ;;; that , You need to call 【 Get user account information , Interface 】 and 【 Get basic user information , Interface 】 To get user information , It can be learned from redsi Take in , Instead of fetching from the database ;
One : Use redis Cache user information , To reduce the pressure on the database ;
1. modify getUser() The logic of the method :redis There is user information in , From redis Take in ;redis There is no user information in , Just look it up in the database , At the same time, save the found user information to redis In the middle ;
Modify us in 【user】 In user microservices 、UserController As defined in 、 according to userId Check it out user Of ,getUser() The logic of the method ;
/** * Common method : according to userId Check it out user; * @param userId * @return */ private AppUser getUser(String userId) { // explain : because “ User information ” It doesn't change very often ; For some ten million level websites , When a user queries user information for the first time , // We can use this information redis cached ; thus , When users get information later , You can start from redis in // obtain , You don't have to query the database ; AppUser user = null; //(1) Go to redis Check it out , see redis Whether the user information of this user already exists in ; String userJson = redisOperator.get(REDIS_USER_INFO + ":" + userId); //(2.1) If redis in , You already have the user's information : Then we will JSON User information in , Convert to corresponding AppUser object ; if (StringUtils.isNotBlank(userJson)) { user = JsonUtils.jsonToPojo(userJson, AppUser.class); } else { //(2.2) If redis in , There is no information about this user ( that , The maximum probability is , This is the first time for users to query user information ), Then we // Just query the database , Get user information from the database ; user = userService.getUser(userId); // meanwhile , Put the found user information , Deposit in redis In the middle ;( In order to , Let users query user information for the second time , Just // Can be directly from redis I got it in the middle , There is no need to operate the database ) redisOperator.set(REDIS_USER_INFO+":"+userId,JsonUtils.objectToJson(user)); } //(2.3) return user User object return user; }
explain :
(1) Modify the content ;
(2) logic analysis ;
● Read notes ;
● because , We have to operate here redis, So this class needs to be injected RedisOperator The object of this tool class ;
● We are turning to redis When storing user information , Its key yes 【redis_user_info: user id】 This format ;
2. When calling 【 modify / Improve user information , Interface 】 After modifying user information , We also need to update it in time redis User information in ;
UserServiceImpl Medium updataUserInfo() Method ;
/** * modify / Improve user information , And activate the user ; * * @param updateUserInfoBO */ @Override public void updateUserInfo(UpdateUserInfoBO updateUserInfoBO) { // Pass it from the front updateUserInfoBO Attribute value in ,copy To a AppUser Go to the object ; AppUser userInfo = new AppUser(); BeanUtils.copyProperties(updateUserInfoBO, userInfo); // Reset its update time userInfo.setUpdatedTime(new Date()); // Set its user status , Set its state to 1( Is activated ); userInfo.setActiveStatus(UserStatus.ACTIVE.type); // and mybatis-plus The routine is basically the same , We use updateByPrimaryKeySelective() Method ( This method only updates those in the database table userInfo In some ,, Nothing will move ); // Instead of using updateByPrimaryKey();( This method will completely update the contents of the database table ,,userInfo There is no the , It will be set to empty ), int result = appUserMapper.updateByPrimaryKeySelective(userInfo); if (result != 1) {// If the return value of the above method is not 1, It means that there is something wrong with the update operation , Then we throw an exception ; GraceException.display(ResponseStatusEnum.USER_UPDATE_ERROR); } // To get to this point , Explain that the user information update is OK Of ; that , At this point, we go to get the latest user information , Save it to redis In the middle ; String userId = updateUserInfoBO.getId(); AppUser user = getUser(userId); redisOperator.set(REDIS_USER_INFO+":"+userId, JsonUtils.objectToJson(user));// This will overwrite the old value }
explain :
(1) Modify the content ;
● because , We have to operate here redis, So this class needs to be injected RedisOperator The object of this tool class ; meanwhile , We are turning to redis When storing user information , Its key The format of , Need to follow 【redis_user_info: user id】 This format ;
Two : effect ;
First, the whole situation install Look at the whole project , Then start 【user】 The main user micro service started ;
meanwhile , To prevent any interference , We cleared the browser cache 、 Database data 、redis Data in the ;
step1: First time registration / The logged in user ;
Our first registration / Log in to a new user ;
then , You will enter the account setting page ;
Let's let go of the breakpoint ; because ,accountInfo.html page , Will visit at the same time 【 Get user account information , Interface 】 and 【 Get basic user information , Interface 】; therefore , It's on the back , Actually, it will be called twice getUser() Methodical ; therefore , We need to release the breakpoint here twice ( stay IDEA in , Can press F9), thus accountInfo.html The data required by the page can be prepared , This page can be fully loaded ;
step2: To update / Improve user information ;
……………………………………………………
natural , After we update the user information ,accountInfo.html The page will reload ;
natural , Because to get “ User account information ”( By visiting 【 Get user account information , Interface 】 get ),,, Also want to get “ Basic information of users ”(Session Storage There is , From Session Storage Take in ;;;Session Storage There is no , Just visit 【 Get basic user information , Interface 】 get ;;; because , When updating user information , The front-end code puts Session Storage The stored users are basically cleared ,,, So it also needs to call 【 Get basic user information , Interface 】 Of );;;; therefore , It's on the back , Actually, it will be called twice getUser() Methodical ;
We need to release the breakpoint here twice ( stay IDEA in , Can press F9), thus accountInfo.html The data required by the page can be prepared , This page can be fully loaded ;
PS: Because in accountInfo.html On ,( If Session Storage There is no “ Basic information of users ” Words ) The backend will be called twice getUser() Method ;;; This is not convenient for us to observe the effect ;;; therefore , We will test on the homepage ;
、
Here is the homepage ;
A front-end 、 Unresolved issues ;
A page is in session storage Created in the “ Basic information of users ”, Can't you use other pages ?( This is the front-end knowledge ~~~~, I don't quite understand )
(1) A description of the situation ;
then ,
however , When we click 【 Muke news 】 after , Get into index.html page ;
(2) doubt ;
problem 1: It's not a good idea ,index.html The page will only try to get “ Basic information of users ” Do you ( Without getting “ User account information ”);;;; since , Is to obtain “ Basic information of users ”;;;; We have saved the basic user information to Session Storage It's in ;;;; Why should it call the back-end interface ;
problem 2: Why? 【 We are accountInfo.html On this page , Save to Session Storage Medium “ Basic information of users ”】, stay index.html View... On the page , But it's gone ?(3) Account for :
● Be reasonable , This ( Mainly the content of the front-end range ) I don't understand the problem very well , Really want to understand , It is estimated that it will take a lot of energy ~~~ Forget it , On hold ~~
● There is nothing wrong here , Mainly for Session Storage In my last blog , I got it wrong at first ;;Session Storage You can't cross windows ; For details, please refer to the previous blog 【32: The third chapter : Developing a pass service :15: Browser storage media , brief introduction ;(cookie,Session Storage,Local Storage)】;
step3:Redis Cache effect demonstration ;
(1)Redis When there is cached data in ;
……………………………………………………
F8 Step by step debugging ,
F9 Let it go after , page OK 了 , Sure Session Storage It's in “ Basic information of users ”;
(2)Redis When there is no cached data in ;
(3) If we put Session Storage Clear the user information in , Refresh the page again , It's from Redis I got ;
边栏推荐
- 机器学习编译第2讲:张量程序抽象
- Excuse me, is the redis syntax used in DMS based on the commands of the redis community version of the cloud database
- Embedded-c language-6
- Use JDBC technology and MySQL database management system to realize the function of course management, including adding, modifying, querying and deleting course information.
- 启牛商学院股票开户安全吗?靠谱吗?
- MySql 查询符合条件的最新数据行
- 精准防疫有“利器”| 芯讯通助力数字哨兵护航复市
- Etcd build a highly available etcd cluster
- Embedded-c Language-3
- 项目引入jar从私服Nexus 拉去遇到的一个问题
猜你喜欢
Judge whether a number is a prime number (prime number)
Iphone14 with pill screen may trigger a rush for Chinese consumers
中国广电正式推出5G服务,中国移动赶紧推出免费服务挽留用户
CMake教程Step2(添加库)
阈值同态加密在隐私计算中的应用:解读
The second day of learning C language for Asian people
干货!半监督预训练对话模型 SPACE
[first lecture on robot coordinate system]
[Web attack and Defense] WAF detection technology map
Jarvis OJ Telnet Protocol
随机推荐
国产芯片产业链两条路齐头并进,ASML真慌了而大举加大合作力度
Little knowledge about C language (array and string)
Embedded-c language-6
Embedded -arm (bare board development) -1
Use of ThinkPHP template
WSL2.0安装
How to write a full score project document | acquisition technology
Embedded UC (UNIX System Advanced Programming) -3
ECU introduction
Error in composer installation: no composer lock file present.
Iphone14 with pill screen may trigger a rush for Chinese consumers
CMake教程Step1(基本起点)
Excuse me, is the redis syntax used in DMS based on the commands of the redis community version of the cloud database
[Web attack and Defense] WAF detection technology map
Embedded-c Language-2
ThoughtWorks global CTO: build the architecture according to needs, and excessive engineering will only "waste people and money"
Use JDBC technology and MySQL database management system to realize the function of course management, including adding, modifying, querying and deleting course information.
拷贝方式之DMA
The second day of learning C language for Asian people
Embedded-c Language-5