Java面试题 P17:Redis篇:Redis使用场景-缓存-缓存击穿

什么是缓存击穿:给某一个key设置了过期时间,当key过期的时候,恰好这时间点对这个key有大量的并发请求过来,这些并发的请求可能会瞬间把数据库压垮。

 

 

互斥锁代码:

 1 package com.atguigu.boot00testredis.controller;
 2 
 3 import com.atguigu.boot00testredis.utils.RedisUtil;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.web.bind.annotation.GetMapping;
 6 import org.springframework.web.bind.annotation.PathVariable;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RestController;
 9 
10 import java.util.concurrent.locks.Lock;
11 import java.util.concurrent.locks.ReadWriteLock;
12 import java.util.concurrent.locks.ReentrantReadWriteLock;
13 
14 @RestController
15 @RequestMapping("/hello")
16 public class HelloController
17 {
18     /**
19      * 注入redis工具
20      */
21     @Autowired
22     private RedisUtil redisUtil;
23 
24     private final ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
25     //写锁
26     private final Lock writeLock=readWriteLock.writeLock();
27 
28     @GetMapping("/hi/{name}")
29     public String hi(@PathVariable("name") String name)
30     {
31         System.out.println("name="+name);
32 
33         if(redisUtil.get(name)!=null)
34         {
35             return redisUtil.get(name).toString();
36         }
37         else {
38             //加锁
39             writeLock.lock();
40             System.out.println("readLock.......");
41             try{
42                 Thread.sleep(20*1000);
43                 redisUtil.set(name,"My name is "+name+"!",60);
44                 return redisUtil.get(name).toString();
45             }
46             catch (Exception e)
47             {
48                 return null;
49             }
50             finally {
51                 //开锁
52                 writeLock.unlock();
53             }
54         }
55     }
56 }

 

posted on 2023-07-30 23:14  wuzx-blog  阅读(20)  评论(0编辑  收藏  举报