最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot + Mybatis Plus 整合 Redis的詳細步驟

 更新時間:2025年03月18日 10:38:19   作者:測試開發(fā)小白變怪獸  
文章詳細介紹了Redis在用戶管理系統(tǒng)中的應(yīng)用,包括用戶信息緩存、Token存儲、接口限流、重復(fù)提交攔截和熱點數(shù)據(jù)預(yù)加載等場景,并提供了具體的實現(xiàn)方案和步驟,感興趣的朋友一起看看吧

Redis 在用戶管理系統(tǒng)中的典型應(yīng)用場景

結(jié)合你的用戶增刪改查接口,以下是 Redis 的實用場景和具體實現(xiàn)方案:

場景作用實現(xiàn)方案
用戶信息緩存減少數(shù)據(jù)庫壓力,加速查詢響應(yīng)使用 Spring Cache + Redis 注解緩存
登錄 Token 存儲分布式 Session 或 JWT Token 管理將 Token 與用戶信息綁定,設(shè)置過期時間
接口限流防止惡意刷接口基于 Redis 計數(shù)器實現(xiàn)滑動窗口限流
重復(fù)提交攔截防止用戶重復(fù)提交表單用 Redis 存儲請求唯一標(biāo)識,設(shè)置短期過期
熱點數(shù)據(jù)預(yù)加載提前緩存高頻訪問數(shù)據(jù)定時任務(wù) + Redis 存儲

Mac M1 安裝 Redis 詳細步驟

1. 通過 Homebrew 安裝 Redis

# 安裝 Homebrew(如果尚未安裝)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 安裝 Redis
brew install redis

2. 啟動 Redis 服務(wù)

# 前臺啟動(測試用,Ctrl+C 退出)
redis-server
# 后臺啟動(推薦)
brew services start redis

3. 驗證安裝

# 連接 Redis 客戶端
redis-cli ping  # 應(yīng)返回 "PONG"

Spring Boot 3 整合 Redis

1. 添加依賴

pom.xml 中:

		<!-- Spring Cache 核心依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!-- Redis 驅(qū)動 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

2. 配置 Redis 連接

application.yml

spring:
  data:
    redis:
      host: localhost
      port: 6379
      # password: your-password  # 如果設(shè)置了密碼
      lettuce:
        pool:
          max-active: 8
          max-idle: 8

3. 示例

配置類

package com.example.spring_demo01.config;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
@Configuration
public class RedisConfig {
    // 配置 RedisTemplate
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // Key 序列化
        template.setKeySerializer(new StringRedisSerializer());
        // Value 序列化為 JSON
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // Hash 結(jié)構(gòu)序列化
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
    // 配置緩存管理器
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .entryTtl(Duration.ofMinutes(30)); // 設(shè)置默認過期時間
        return RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
    }
}

接口限流工具類

package com.example.spring_demo01.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Component
public class RateLimiter {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    public boolean allowRequest(String userId) {
        String key = "rate_limit:" + userId;
        long now = System.currentTimeMillis();
        long windowMs = 60_000; // 1 分鐘
        // 移除窗口外的請求記錄
        redisTemplate.opsForZSet().removeRangeByScore(key, 0, now - windowMs);
        // 統(tǒng)計當(dāng)前窗口內(nèi)請求數(shù)
        Long count = redisTemplate.opsForZSet().zCard(key);
        if (count != null && count >= 10) {
            return false; // 超過限制
        }
        // 記錄本次請求
        redisTemplate.opsForZSet().add(key, UUID.randomUUID().toString(), now);
        redisTemplate.expire(key, windowMs, TimeUnit.MILLISECONDS);
        return true;
    }
}

實體類

package com.example.spring_demo01.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.io.Serializable;
@Data
@TableName("user")
@JsonIgnoreProperties(ignoreUnknown = true) // 防止 JSON 反序列化問題
public class User implements Serializable { // 實現(xiàn) Serializable
    @TableId(type = IdType.AUTO) // 主鍵自增
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

service層

package com.example.spring_demo01.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.spring_demo01.entity.User;
import com.example.spring_demo01.mapper.UserMapper;
import com.example.spring_demo01.service.UserService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.io.Serializable;
@Service
public class UserServiceImpl
        extends ServiceImpl<UserMapper, User>
        implements UserService {
    // 對 MyBatis Plus 的 getById 方法添加緩存
    @Cacheable(value = "user", key = "#id")
    @Override
    public User getById(Serializable id) {
        return super.getById(id);
    }
    // 更新時清除緩存
    @CacheEvict(value = "user", key = "#entity.id")
    @Override
    public boolean updateById(User entity) {
        return super.updateById(entity);
    }
    // 刪除時清除緩存
    @CacheEvict(value = "user", key = "#id")
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }
}

controller層

package com.example.spring_demo01.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.spring_demo01.annotation.AdminOnly;
import com.example.spring_demo01.entity.User;
import com.example.spring_demo01.service.UserService;
import com.example.spring_demo01.utils.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.time.Duration;
import java.util.List;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RateLimiter rateLimiter;
    // ------------------------------ 增 ------------------------------
    @PostMapping
    public String addUser(@RequestBody User user, @RequestHeader String clientId) {
        String key = "SUBMIT_LOCK:" + clientId + ":" + user.hashCode();
        // 10秒內(nèi)不允許重復(fù)提交
        Boolean success = redisTemplate.opsForValue()
                .setIfAbsent(key, "", Duration.ofSeconds(10));
        if (Boolean.FALSE.equals(success)) {
            throw new RuntimeException("請勿重復(fù)提交");
        }
        userService.save(user);
        return "新增成功";
    }
    // ------------------------------ 刪 ------------------------------
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.removeById(id);
        return "刪除成功";
    }
    @DeleteMapping("/batch")
    public String deleteBatch(@RequestBody List<Long> ids) {
        userService.removeByIds(ids);
        return "批量刪除成功";
    }
    // ------------------------------ 改 ------------------------------
    @PutMapping
    public String updateUser(@RequestBody User user) {
        userService.updateById(user);
        return "更新成功";
    }
    // ------------------------------ 查 ------------------------------
    @GetMapping("/{id}")
    @AdminOnly
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id);
    }
    @GetMapping("/list")
    public List<User> listUsers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer age) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (name != null) {
            wrapper.like("name", name); // 模糊查詢姓名
        }
        if (age != null) {
            wrapper.eq("age", age);     // 精確查詢年齡
        }
        return userService.list(wrapper);
    }
    @GetMapping("/page")
    public Page<User> pageUsers(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestHeader(value = "Authorization") String token) {
        // 從 Token 中獲取用戶ID
        log.info("token:{}", token);
        log.info("User:{}", redisTemplate.opsForValue().get(token.split(" ")[1]));
        User user = (User) redisTemplate.opsForValue().get(token.split(" ")[1]);
        if (user == null) throw new RuntimeException("未登錄");
        // 限流校驗
        if (!rateLimiter.allowRequest("PAGE_" + user.getId())) {
            throw new RuntimeException("請求過于頻繁");
        }
        return userService.page(new Page<>(pageNum, pageSize));
    }
    // ------------------------------ other ------------------------------
    @GetMapping("/error")
    public String getError() {
        throw new RuntimeException();
    }
    @PostMapping("/login")
    public String login(@RequestBody User user) {
        log.info("login user:{}", user);
        // 驗證用戶邏輯(示例簡化)
        User dbUser = userService.getOne(new QueryWrapper<User>()
                .eq("id", user.getId())
                .eq("name", user.getName()));
        if (dbUser == null) {
            throw new RuntimeException("登錄失敗");
        }
        // 生成 Token 并存儲
        String token = "TOKEN_" + UUID.randomUUID();
        redisTemplate.opsForValue().set(
                token,
                dbUser,
                Duration.ofMinutes(30)
        );
        return token;
    }
}

在啟動類添加注解:

package com.example.spring_demo01;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@MapperScan("com.example.spring_demo01.mapper")
@ServletComponentScan // 啟用 Servlet 組件掃描(如 Filter、Servlet)
@EnableCaching // 啟動緩存,Redis使用
public class SpringDemo01Application {
    public static void main(String[] args) {
        SpringApplication.run(SpringDemo01Application.class, args);
    }
}

常見問題排查

Q1: 連接 Redis 超時

  • 檢查服務(wù)狀態(tài):運行 redis-cli ping 確認 Redis 是否正常運行
  • 查看端口占用lsof -i :6379
  • 關(guān)閉防火墻sudo ufw allow 6379

Q2: Spring Boot 無法注入 RedisTemplate

  • 確認配置類:添加 @EnableCaching 和 @Configuration
  • 檢查序列化器:顯式配置序列化方式避免 ClassCastException
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

總結(jié)

通過 Redis 你可以為項目快速實現(xiàn):

  • 高性能緩存層 - 降低數(shù)據(jù)庫負載
  • 分布式會話管理 - 支持橫向擴展
  • 精細化流量控制 - 保障系統(tǒng)穩(wěn)定性

到此這篇關(guān)于SpringBoot + Mybatis Plus 整合 Redis的詳細步驟的文章就介紹到這了,更多相關(guān)SpringBoot Mybatis Plus 整合 Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java拋出異常與finally實例解析

    java拋出異常與finally實例解析

    這篇文章主要介紹了java拋出異常與finally實例解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-10-10
  • 解決idea配置Tomcat Deployment沒有artifact選項的問題

    解決idea配置Tomcat Deployment沒有artifact選項的問題

    今天在配置的時候tomcat deployment中卻找不到artifact,沒有artifact就不能打成war包上傳到服務(wù)器了,那么怎么解決沒有artifact選項的問題呢,今天通過本文給大家分享idea配置Tomcat Deployment沒有artifact選項的解決方案,一起看看吧
    2023-10-10
  • 深入剖析Java中Map.Entry的方法與實戰(zhàn)應(yīng)用

    深入剖析Java中Map.Entry的方法與實戰(zhàn)應(yīng)用

    在Java集合框架中,Map.Entry扮演著連接鍵值對的橋梁角色,作為Map接口的內(nèi)部接口,它封裝了鍵值對的本質(zhì),是高效處理映射數(shù)據(jù)的核心工具,下面我我們就來深入剖析Map.Entry的概念,方法及實戰(zhàn)應(yīng)用
    2025-06-06
  • Mybatis日志模塊的適配器模式詳解

    Mybatis日志模塊的適配器模式詳解

    這篇文章主要介紹了Mybatis日志模塊的適配器模式詳解,,mybatis用了適配器模式來兼容這些框架,適配器模式就是通過組合的方式,將需要適配的類轉(zhuǎn)為使用者能夠使用的接口
    2022-08-08
  • Java集合框架Set&Map詳細解析

    Java集合框架Set&Map詳細解析

    這篇文章介紹了Java集合框架中的Map和Set接口,Map接口用于存儲鍵值對,常用實現(xiàn)類有HashMap、LinkedHashMap和TreeMap,Set接口用于存儲唯一元素,常用實現(xiàn)類有HashSet、LinkedHashSet和TreeSet,每種實現(xiàn)類都有其特點和適用場景,感興趣的朋友跟隨小編一起看看吧
    2025-11-11
  • 使用MAT進行JVM內(nèi)存分析實例

    使用MAT進行JVM內(nèi)存分析實例

    這篇文章主要介紹了使用MAT進行JVM內(nèi)存分析實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • 詳解Java?redis中緩存穿透?緩存擊穿?雪崩三種現(xiàn)象以及解決方法

    詳解Java?redis中緩存穿透?緩存擊穿?雪崩三種現(xiàn)象以及解決方法

    緩存穿透是指緩存和數(shù)據(jù)庫中都沒有的數(shù)據(jù),而用戶不斷發(fā)起請求,如發(fā)起為id為“-1”的數(shù)據(jù)或id為特別大不存在的數(shù)據(jù)。這時的用戶很可能是攻擊者,攻擊會導(dǎo)致數(shù)據(jù)庫壓力過大
    2022-01-01
  • 淺談SpringMVC中的session用法及細節(jié)記錄

    淺談SpringMVC中的session用法及細節(jié)記錄

    下面小編就為大家?guī)硪黄獪\談SpringMVC中的session用法及細節(jié)記錄。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • java獲取properties屬性文件示例

    java獲取properties屬性文件示例

    Properties類表示了一個持久的屬性集。Properties可保存在流中或從流中加載。屬性列表中每個鍵及其對應(yīng)值都是一個字符串。本文使用java讀取這些屬性,看下面詳細介紹吧
    2014-01-01
  • 學(xué)習(xí)不同 Java.net 語言中類似的函數(shù)結(jié)構(gòu)

    學(xué)習(xí)不同 Java.net 語言中類似的函數(shù)結(jié)構(gòu)

    這篇文章主要介紹了學(xué)習(xí)不同 Java.net 語言中類似的函數(shù)結(jié)構(gòu),函數(shù)式編程語言包含多個系列的常見函數(shù)。但開發(fā)人員有時很難在語言之間進行切換,因為熟悉的函數(shù)具有不熟悉的名稱。函數(shù)式語言傾向于基于函數(shù)范例來命名這些常見函數(shù)。,需要的朋友可以參考下
    2019-06-06

最新評論

庆城县| 秦安县| 侯马市| 措美县| 左权县| 彰化市| 道真| 青河县| 台湾省| 麟游县| 进贤县| 肃宁县| 桓台县| 新沂市| 玉环县| 额敏县| 宁津县| 中超| 密山市| 崇礼县| 苏尼特左旗| 安阳县| 运城市| 香港| 武功县| 沂南县| 开原市| 怀集县| 龙州县| 长宁县| 肥东县| 扎鲁特旗| 东光县| 板桥市| 宜川县| 汉川市| 浦北县| 扎鲁特旗| 甘德县| 鄂托克旗| 达日县|