SpringBoot集成Redis

1、爲何要使用Redis?

  • 性能極高 – Redis讀的速度是110000次/s,寫的速度是81000次/s ;
  • 豐富的數據類型 – Redis支持Strings, Lists, Hashes, Sets 及 Ordered Sets 數據類型操做;
  • 原子 – Redis的全部操做都是原子性的,即要麼成功執行要麼失敗徹底不執行。單個操做是原子性的。多個操做也支持事務,即原子性,經過MULTI和EXEC指令包起來;

*豐富的特性 – Redis還支持publish/subscribe, key過時等特性。html

2、什麼狀況應該使用Redis?

  • 會話緩存(如分佈式應用存儲token等);
  • 計數器(如一天以內密碼輸錯了三次,自動鎖定帳戶);
  • 熱點數據(如排名等);
  • 緩解數據庫壓力(MyBatis或MyBatis-Plus使用Redis作二級緩存);
  • 定時器(主要針對redis的key過時時間)。

3、整合Redis

1.導入Maven依賴

<!-- Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.配置文件application.yml修改

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password:

3.Controller測試(可複用SpringBoot整合MyBatis-Plus例子)

package com.blog.tutorial.controller;
import com.blog.tutorial.entity.Users;
import com.blog.tutorial.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * @description:
 * @author: youcong
 * @time: 2020/11/14 13:27
 */@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
 private UsersService usersService;
    @Autowired
 private RedisTemplate redisTemplate;
    @GetMapping("/list")
    public String list() {
        System.out.println("list:"+redisTemplate.opsForValue().get("list"));
        if (StringUtils.isEmpty(redisTemplate.opsForValue().get("list"))) {
            redisTemplate.opsForValue().set("list", usersService.list(), 360, TimeUnit.MINUTES);
        }
        return redisTemplate.opsForValue().get("list").toString();
    }
}

4.測試效果

請求接口,以下:
image.pngjava

控制檯,以下:
image.pngweb

初次請求,會打印SQL,再次請求只會輸出Redis的key,同時頁面接口響應時間很是快。redis

4、Redis常見問題有哪些?

  • 緩存和數據庫雙寫一致性(緩存的數據與數據庫查詢的數據不同);
  • 緩存雪崩(即緩存同一時間大面積的失效,這個時候又來了一波請求,結果請求都懟到數據庫上,從而致使數據庫鏈接異常);
  • 緩存擊穿(黑客故意去請求緩存中不存在的數據,致使全部的請求都懟到數據庫上,從而數據庫鏈接異常);
  • 緩存併發競爭(多個系統同時set同一個key,涉及分佈式鎖)。

5、Java的Redis框架有哪些?

  • Jedis;
  • Lettuce;
  • Redisson。

關於上述框架使用,我在個人博客園寫下以下幾篇文章,感興趣的能夠看看:
SpringBoot整合Redisson\(單機版\)spring

SpringBoot實戰\(七\)之與Redis進行消息傳遞數據庫

SpringBoot整合Redisson\(集羣版\)緩存

redis集羣搭建性能優化

Java鏈接Redis之redis的增刪改查併發

網站性能優化小結和spring整合redisapp

相關文章
相關標籤/搜索