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
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...