緩存穿透只會發生在高併發的時候,就是當有10000個併發進行查詢數據的時候,咱們通常都會先去redis裏面查詢進行數據,可是若是redis裏面沒有這個數據的時候,那麼這10000個併發裏面就會有很大一部分併發會一會兒都去mysql數據庫裏面進行查詢了html
好比下面的代碼 Pom.xml代碼java
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath></relativePath> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Application.propertiesmysql
server.port=8081 #DB Configuration: spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://47.91.248.236:3306/hello?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root #spring集成Mybatis環境 #pojo別名掃描包 mybatis.type-aliases-package=com.itheima.domain #加載Mybatis映射文件 mybatis.mapper-locations=classpath:mapper/*Mapper.xml
MyController代碼,下面的藍色代碼是模仿10000個併發線程web
/** * sinture.com Inc. * Copyright (c) 2016-2018 All Rights Reserved. */ package com.itheima.controller; import com.itheima.mapper.UserMapper; import com.itheima.domain.User; import com.itheima.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author xinzhu * @version Id: MyController.java, v 0.1 2018年12月05日 下午6:29 xinzhu Exp $ */ @RestController public class MyController { @Autowired private UserService userService; @RequestMapping("/hello/{id}") @ResponseBody public User queryUser(@PathVariable Integer id){ // 藍色代碼註釋開始 new Thread(){ @Override public void run() { for (int x = 0; x < 10000; x++) { userService.queryUser(id); } } }.start(); // 藍色代碼註釋結束 return userService.queryUser(id); } }
User類redis
/** * sinture.com Inc. * Copyright (c) 2016-2018 All Rights Reserved. */ package com.itheima.domain; /** * @author xinzhu * @version Id: User.java, v 0.1 2018年12月06日 下午1:40 xinzhu Exp $ */ public class User { // 主鍵 private Integer id; // 用戶名 private String username; // 密碼 private String password; // 姓名 private String name; public void setId(Integer id) { this.id = id; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", name='" + name + '\'' + '}'; } public Integer getId() { return id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
UserServicespring
package com.itheima.service; import com.itheima.domain.User; public interface UserService { public User queryUser(Integer id); }
UserServiceImpl,下面的藍色代碼就是模仿redis,此時要注意下面的模擬redis的map集合必須放到下面的queryUser的外面,也就是說下面的userMap變量必須是成員變量,否則的話,由於redis是被多個線程共享的,若是你放到下面的queryUser()方法裏面,那麼就是多個線程有多個userMap集合,下面的代碼就是若是查詢到數據,那麼就用redis裏面的,若是查詢不到就用數據庫裏面的sql
package com.itheima.service; import com.itheima.domain.User; import com.itheima.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; // 藍色代碼註釋開始 static Map<Integer,User> userMap=new HashMap(); static { User huancun_user =new User(); huancun_user.setId(1); huancun_user.setName("zhangsan"); huancun_user.setPassword("123"); huancun_user.setName("張三"); userMap.put(1,huancun_user); } // 藍色代碼註釋結束 public User queryUser(Integer id){ User user=userMap.get(id); if(user==null){ user= userMapper.queryUser(id); System.out.println("查詢數據庫"); userMap.put(user.getId(),user); }else{ System.out.println("查詢緩存"); } return user; }; }
SpringbootApplication代碼數據庫
package com.itheima; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
數據庫裏面的數據以下apache
-- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '張三'); INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');
而後咱們查詢下面的連接,由於此時上面的模擬redis的map集合裏面沒有id值是2的數據,因此此時都是查詢數據庫,你想這一會兒10000併發過去,數據庫會有很大壓力的,緩存
而後打印結果以下,就是打印了不少查詢數據庫和查詢緩存,此時也就說明10000個併發裏面有不少去查詢了數據庫,這個是要避免的,至於爲何有查詢緩存的打印,由於咱們把查詢的數據給放到模擬的redis裏面了啊,因此剛開始的一大部分線程都是查詢數據庫,而後剩下的都是查詢模擬的redis緩存裏面的數據
查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢數據庫 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存
咱們怎麼解決緩存穿透呢,即便10000個併發過來,而後這10000個併發須要的數據在redis裏面都沒有,那麼咱們應該第一個線程查詢數據裏面的數據,而後把這個數據給放到redis裏面,而後剩下的9999個線程都到redis裏面查詢,這樣就解決了緩存穿透,因此咱們能夠把上面的代碼變成下面這樣
好比下面的代碼
Pom.xml代碼
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath></relativePath> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Application.properties
server.port=8081 #DB Configuration: spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://47.91.248.236:3306/hello?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=root #spring集成Mybatis環境 #pojo別名掃描包 mybatis.type-aliases-package=com.itheima.domain #加載Mybatis映射文件 mybatis.mapper-locations=classpath:mapper/*Mapper.xml
MyController代碼,下面的藍色代碼是模仿10000個併發線程
/** * sinture.com Inc. * Copyright (c) 2016-2018 All Rights Reserved. */ package com.itheima.controller; import com.itheima.mapper.UserMapper; import com.itheima.domain.User; import com.itheima.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author xinzhu * @version Id: MyController.java, v 0.1 2018年12月05日 下午6:29 xinzhu Exp $ */ @RestController public class MyController { @Autowired private UserService userService; @RequestMapping("/hello/{id}") @ResponseBody public User queryUser(@PathVariable Integer id){ // 藍色代碼註釋開始 new Thread(){ @Override public void run() { for (int x = 0; x < 10000; x++) { userService.queryUser(id); } } }.start(); // 藍色代碼註釋結束 return userService.queryUser(id); } }
User類
/** * sinture.com Inc. * Copyright (c) 2016-2018 All Rights Reserved. */ package com.itheima.domain; /** * @author xinzhu * @version Id: User.java, v 0.1 2018年12月06日 下午1:40 xinzhu Exp $ */ public class User { // 主鍵 private Integer id; // 用戶名 private String username; // 密碼 private String password; // 姓名 private String name; public void setId(Integer id) { this.id = id; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", name='" + name + '\'' + '}'; } public Integer getId() { return id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
UserService
package com.itheima.service; import com.itheima.domain.User; public interface UserService { public User queryUser(Integer id); }
UserServiceImpl,下面的藍色代碼就是模仿redis,此時要注意下面的模擬redis的map集合必須放到下面的queryUser的外面,也就是說下面的userMap變量必須是成員變量,否則的話,由於redis是被多個線程共享的,若是你放到下面的queryUser()方法裏面,那麼就是多個線程有多個userMap集合,下面的代碼就是若是查詢到數據,那麼就用redis裏面的,若是查詢不到就用數據庫裏面的
而後下面的紅色代碼就是解決上面的緩存穿透問題,使用鎖來解決緩存穿透問題,並且叫作雙重檢測鎖,爲何叫作雙重檢測鎖呢,由於有兩個if語句,第一個if語句就是爲了減小走紅色代碼裏面的同步代碼塊,由於若是換成裏面存在想要的數據,那麼就不須要走下面的紅色代碼裏面的同步代碼塊了,因此有兩個if語句,至於爲何要有下面的 user= userMap.get(id);,是由於第一次線程查詢把數據放到模仿的redis緩存裏面以後,剩下的線程當走到下面的同步代碼塊的時候,須要在查詢一下緩存裏面的數據就會發現剛剛第一個線程放到redis裏面的數據了,因此纔會有下面的紅色代碼裏面的 user= userMap.get(id);
package com.itheima.service; import com.itheima.domain.User; import com.itheima.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; // 藍色代碼註釋開始 static Map<Integer,User> userMap=new HashMap(); static { User huancun_user =new User(); huancun_user.setId(1); huancun_user.setName("zhangsan"); huancun_user.setPassword("123"); huancun_user.setName("張三"); userMap.put(1,huancun_user); } // 藍色代碼註釋結束 public User queryUser(Integer id){ User user=userMap.get(id); // 紅色代碼註釋開始 if(user==null){ synchronized (this) { user= userMap.get(id); if (null == user) { user= userMapper.queryUser(id); System.out.println("查詢數據庫"); userMap.put(user.getId(),user); }else{ System.out.println("查詢緩存"); } } }else{ System.out.println("查詢緩存"); } //紅色代碼註釋結束 return user; }; }
數據庫裏面的數據以下
-- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '張三'); INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');
而後咱們查詢下面的連接,由於此時上面的模擬redis的map集合裏面沒有id值是2的數據,因此此時都是查詢數據庫,你想這一會兒10000併發過去,數據庫會有很大壓力的, 而後打印結果以下,就是就只有第一個打印了查詢數據庫,而後剩下的都是查詢緩存了,這就是解決緩存穿透
查詢數據庫 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存 查詢緩存
<font color=red>能看到這裏的同窗,就幫忙點個推薦吧,Thanks♪(・ω・)ノ</font>
原文出處:https://www.cnblogs.com/mqk100/p/11319758.html