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
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...