springboot整合redis-SpringBoot(22)

来源:https://www.cnblogs.com/liwenruo/archive/2022/08/12/16578404.html
-Advertisement-
Play Games

1. 在 Spring Boot 中集成 Redis (1)完成配置基礎項。 添加 Redis、MySQL、MyBatis 依賴。 (2)配置MySQL、Redis伺服器 可以直接在application.yml文件中逬行配置,具體配置方法見以下代碼: 查看代碼 # 應用名稱 spring: red ...


1. 在 Spring Boot 中集成 Redis

  (1)完成配置基礎項。

    添加 Redis、MySQL、MyBatis 依賴。

  (2)配置MySQL、Redis伺服器

    可以直接在application.yml文件中逬行配置,具體配置方法見以下代碼:

查看代碼

# 應用名稱
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 5000
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
      username: root
      password: 123456
    thymeleaf:
      mode: HTML
      encoding: UTF-8
      servlet:
        content-type: text/html
      cache: false
      prefix: classpath:/static/

mybatis:
  # spring boot集成mybatis的方式列印sql
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 應用服務 WEB 訪問埠
server:
  port: 8080

  (3)在入口類加上@EnableCaching註解,開啟緩存支持。

2. 配置Redis類

  要想啟用Spring緩存支持,需創建一個CacheManager的Bean

package com.intehel.demo.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.StringRedisTemplate;
import java.lang.reflect.Method;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    //在緩存對象集合中,緩存是以key-value形式保存的
    //如果沒有指定緩存的key,則Spring Boot 會使用SimpleKeyGenerator生成key
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            //定義緩存key的生成策略
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    @SuppressWarnings("rawtypes")
    @Bean
    //緩存管理器 2.X版本
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory);
        return cacheManager;
    }
    //緩存管理器 1.X版本
/*    public CacheManager cacheManager(@SuppressWarnings("rawtypes")RedisTemplate redisTemplate){
        return new RedisCacheManager(redisTemplate);
    }*/

    @Bean
    //註冊成Bean被Spring管理,如果沒有這個Bean,則Redis可視化工具中的中文內容都會以二進位存儲,不易檢查
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<String,Object>();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}

3.創建測試實體類

  創建用於數據操作的測試實體類,見以下代碼:

package com.intehel.demo.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
    private Long id;
    private String name;
    private Integer age;
    private String address;
}

4. 實現實體和數據表的映射關係

package com.intehel.demo.mapper;

import com.intehel.demo.domain.Person;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface PersonMapper {
    @Insert("insert into person(name, age,address) values(#{name},#{age},#{address})")
    int addPerson(@Param("name")String name, @Param("age")String age, @Param("address")String address);
    @Select("select * from person where id = #{id}")
    Person findById(@Param("id")String id);
    @Update("update person set age = #{age},name = #{name},address = #{address} where id = #{id}")
    int updateById(Person person);
    @Delete("delete from person where id = #{id}")
    void deleteById(@Param("id")String id);
}

5. 創建Redis緩存服務層

package com.intehel.demo.service;

import com.intehel.demo.domain.Person;
import com.intehel.demo.mapper.PersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "person")
public class PersonService {
    @Autowired
    PersonMapper personMapper;
    @Cacheable(key = "#p0")
    public Person selectPerson(String id){
        System.out.println("selectPerson");
        return personMapper.findById(id);
    }
    @CachePut(key = "#p0")
    public void updatePerson(Person person){
        System.out.println("updatePerson");
        personMapper.updateById(person);
    }
    @CacheEvict(key = "#p0",allEntries = true)
    public void deletePerson(String id){
        System.out.println("deletePerson");
        personMapper.deleteById(id);}
}

代碼解釋如下。

  • @Cacheable:將查詢結果緩存到Redis中。
  • key="#p0":指定傳入的第1個參數作為Redis的key。
  • @CachePut:指定key, 將更新的結果同步到Redis中。
  • @CacheEvict:指定key, 刪除緩存數據。
  • @allEntries=true:方法調用後將立即清除緩存

6.完成增加、刪除、修改和查詢測試API

package com.intehel.demo.controller;

import com.intehel.demo.service.PersonService;
import com.intehel.demo.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class PersonController {
    @Autowired
    PersonService personService;
    @RequestMapping(value = "/{id}")
    public Person selectPerson(@PathVariable String id){
        return personService.selectPerson(id);
    }
    @RequestMapping(value = "/update")
    public String updatePerson(@RequestBody Person person){
        personService.updatePerson(person);
        return "success";
    }
    @RequestMapping(value = "/delete/{id}")
    public String deletePerson(@PathVariable String id){
        personService.deletePerson(id);
        return "delete success";
    }
}

  啟動項目,多次訪問http://localhost:8080/user/1 第一次時控制台會出現select信息,代表對資料庫進行了查詢操作。後面再訪問時則不會出現提示,表示沒有對資料庫執行操作,而是使用 Redis中的緩存數據。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • js 中 正則表達式使用 創建正則對象和test方法使用 /* 創建正則表達式的對象 語法: var 變數 = new RegExp("正則表達式","匹配模式") 或者 var 變數 = /正則表達式/ 匹配模式: i:忽略大小寫 。 g:全局匹配模式 */ //var reg = new Reg ...
  • vite打包異常,錯誤信息如下: [vite]: Rollup failed to resolve import "element-plus/es/components" from "node_modules/element-plus/es/index.js". This is most likel ...
  • 背景 項目中用到了vue的element-ui框架,用到了el-tree組件。由於數據量很大,使用了數據懶載入模式,即非同步樹。非同步樹採用覆選框進行結點選擇的時候,沒法自動展開,官方文檔找了半天也沒有找到好的辦法! 找不到相關的配置,或者方法可以使用。 經過調試與閱讀elment-ui源碼才發現有現成 ...
  • 蒼穹之邊,浩瀚之摯,眰恦之美; 悟心悟性,善始善終,惟善惟道! —— 朝槿《朝槿兮年說》 寫在開頭 我國宋代禪宗大師青原行思在《三重境界》中有這樣一句話:“ 參禪之初,看山是山,看水是水;禪有悟時,看山不是山,看水不是水;禪中徹悟,看山仍然山,看水仍然是水。” 作為一名Java Developer, ...
  • 在應用程式開發中,一般要求儘量兩做到可維護性和可復用性。應用程式的復用可以提高應用程式的開發效率和質量,節約開發成本,恰當的復用還可以改善系統的可維護性。而在面向對象的設計裡面,可維護性復用都是以面向對象設計原則為基礎的,這些設計原則首先都是復用的原則。遵循這些設計原則可以有效地提高系統的復用性,同... ...
  • 1、什麼是設計模式? 設計模式(Design pattern)代表了最佳的實踐,通常被有經驗的面向對象的軟體開發人員所採用。設計模式是軟體開發人員在軟體開發過程中面臨的一般問題的解決方案。這些解決方案是眾多軟體開發人員經過相當長的一段時間的試驗和錯誤總結出來的。 設計模式是一套被反覆使用的、多數人知 ...
  • 轉行做嵌入式也有一段時間了,原來做c#以及一些其它的上層語言, 本想的是也就是僅僅是語法上有點不一樣。但是實際使用的切身體會真的是只有自己才知道。很多方面刷新了我對c語言以及電腦結構體系的認知 ,絕對不僅僅是語法不一樣那麼簡單。 關於字元串傳遞函數引起的 一切源於給函數傳遞字元串變數這種 原來在其 ...
  • 目錄 一.簡介 二.效果演示 三.源碼下載 四.猜你喜歡 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 轉場 零基礎 O ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...