当前位置:网站首页>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 ;
边栏推荐
- 云安全日报220705:红帽PHP解释器发现执行任意代码漏洞,需要尽快升级
- China Radio and television officially launched 5g services, and China Mobile quickly launched free services to retain users
- Q2 encryption market investment and financing report in 2022: gamefi becomes an investment keyword
- 7.Scala类
- 国内首家 EMQ 加入亚马逊云科技「初创加速-全球合作伙伴网络计划」
- 一文了解MySQL事务隔离级别
- Jarvis OJ simple network management protocol
- CMake教程Step4(安装和测试)
- What is ROM
- Use byte stream to read Chinese from file to console display
猜你喜欢
阈值同态加密在隐私计算中的应用:解读
Embedded -arm (bare board development) -1
国内首家 EMQ 加入亚马逊云科技「初创加速-全球合作伙伴网络计划」
Deeply cultivate 5g, and smart core continues to promote 5g applications
The survey shows that the failure rate of traditional data security tools in the face of blackmail software attacks is as high as 60%
[729. My Schedule i]
IDC报告:腾讯云数据库稳居关系型数据库市场TOP 2!
精准防疫有“利器”| 芯讯通助力数字哨兵护航复市
Three traversal methods of binary tree
【机器人坐标系第一讲】
随机推荐
Little knowledge about C language (array and string)
【7.7直播预告】《SaaS云原生应用典型架构》大咖讲师教你轻松构建云原生SaaS化应用,难题一一击破,更有华为周边好礼等你领!
Q2 encryption market investment and financing report in 2022: gamefi becomes an investment keyword
编译libssh2报错找不到openssl
ECU introduction
Writing method of twig array merging
Learnopongl notes (II) - Lighting
【beanshell】数据写入本地多种方法
Practical example of propeller easydl: automatic scratch recognition of industrial parts
EasyX second lesson
mysql如何使用JSON_EXTRACT()取json值
国内首家 EMQ 加入亚马逊云科技「初创加速-全球合作伙伴网络计划」
C# TCP如何限制单个客户端的访问流量
7.Scala类
Browser rendering principle and rearrangement and redrawing
网上办理期货开户安全吗?网上会不会骗子比较多?感觉不太靠谱?
goto Statement
Using C language to realize palindrome number
Iphone14 with pill screen may trigger a rush for Chinese consumers
浏览器渲染原理以及重排与重绘