和get redis_SpringBoot整合Redis,你get了嗎?

Our-task介紹

本篇博客是我github上our-task:一個完整的清單管理系統的配套教程文檔,這是SpringBoot+Vue開發的前后端分離清單管理工具,仿滴答清單。目前已部署在阿里云ECS上,可進行在線預覽,隨意使用(附詳細教程),大家感興趣的話,歡迎給個star!

阿里云預覽地址

Redis的安裝與配置

Windows下redis的安裝與配置

SpringBoot整合Redis

添加項目依賴

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
?<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--redis依賴配置--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
</dependencies>

yml文件配置

yml文件中主要是關于Redis的配置,其中鍵的設置格式為:數據庫名:表名:id,更多Redis了解,請大家參考這篇文章。

Redis各種鍵的典型使用場景,不清楚的都來看一下

# DataSource Config
spring:redis:# Redis服務器地址host: localhost# Redis數據庫索引(默認為0)database: 0# Redis服務器連接端口port: 6379# Redis服務器連接密碼(默認為空)password:jedis:pool:# 連接池最大連接數(使用負值表示沒有限制)max-active: 8# 連接池最大阻塞等待時間(使用負值表示沒有限制)max-wait: -1ms# 連接池中的最大空閑連接max-idle: 8# 連接池中的最小空閑連接min-idle: 0# 連接超時時間(毫秒)timeout: 3000ms
?
# 自定義redis key
redis:database: "study"key:user: "user"expire:common: 86400 # 24小時

實體類

新建entity包,在該包下新建User類,用作該Demo的操作實體。考慮到一些小白可能還不了解Lombok,我就直接使用Setter/Getter。

package com.example.demo.entity;
?
/*** @program: SpringBoot-Redis-Demo* @description: 用戶類* @author: water76016* @create: 2020-12-29 09:22**/
public class User {Integer id;String username;String password;
?public User(Integer id, String username, String password) {this.id = id;this.username = username;this.password = password;}
?@Overridepublic String toString() {return "User{" +"username='" + username + ''' +", password='" + password + ''' +'}';}
?public Integer getId() {return id;}
?public void setId(Integer id) {this.id = id;}
?public String getUsername() {return username;}
?public void setUsername(String username) {this.username = username;}
?public String getPassword() {return password;}
?public void setPassword(String password) {this.password = password;}
}

Service服務接口

服務接口一共有兩個:一個是UserService,一個是RedisService。UserService提供了針對User實體的服務,RedisService提供操作Reids的服務接口。

package com.example.demo.service;
?
import com.example.demo.entity.User;
?
public interface UserService {/*** 對用戶打招呼,返回user的toString()方法* @param user* @return*/public String helloUser(User user);
}
package com.example.demo.service;
?
import java.util.List;
import java.util.Map;
import java.util.Set;
?
?
/*** @program: our-task* @description: redis操作服務類* @author: water76016* @create: 2020-09-24 16:45**/
public interface RedisService {
?/*** 保存屬性** @param key   the key* @param value the value* @param time  the time*/void set(String key, Object value, long time);
?/*** 保存屬性** @param key   鍵* @param value 值*/void set(String key, Object value);
?/*** 獲取屬性** @param key the key* @return the object*/Object get(String key);
?/*** 刪除屬性** @param key the key* @return the boolean*/Boolean del(String key);
?/*** 批量刪除屬性** @param keys the keys* @return the long*/Long del(List<String> keys);
?/*** 設置過期時間** @param key  the key* @param time the time* @return the boolean*/Boolean expire(String key, long time);
?/*** 獲取過期時間** @param key the key* @return the expire*/Long getExpire(String key);
?/*** 判斷是否有該屬性** @param key the key* @return the boolean*/Boolean hasKey(String key);
?/*** 按delta遞增** @param key   the key* @param delta the delta* @return the long*/Long incr(String key, long delta);
?/*** 按delta遞減** @param key   the key* @param delta the delta* @return the long*/Long decr(String key, long delta);
?/*** 獲取Hash結構中的屬性** @param key     the key* @param hashKey the hash key* @return the object*/Object hGet(String key, String hashKey);
?/*** 向Hash結構中放入一個屬性** @param key     the key* @param hashKey the hash key* @param value   the value* @param time    the time* @return the boolean*/Boolean hSet(String key, String hashKey, Object value, long time);
?/*** 向Hash結構中放入一個屬性** @param key     the key* @param hashKey the hash key* @param value   the value*/void hSet(String key, String hashKey, Object value);
?/*** 直接獲取整個Hash結構** @param key the key* @return the map*/Map<Object, Object> hGetAll(String key);
?/*** 直接設置整個Hash結構** @param key  the key* @param map  the map* @param time the time* @return the boolean*/Boolean hSetAll(String key, Map<String, Object> map, long time);
?/*** 直接設置整個Hash結構** @param key the key* @param map the map*/void hSetAll(String key, Map<String, Object> map);
?/*** 刪除Hash結構中的屬性** @param key     the key* @param hashKey the hash key*/void hDel(String key, Object... hashKey);
?/*** 判斷Hash結構中是否有該屬性** @param key     the key* @param hashKey the hash key* @return the boolean*/Boolean hHasKey(String key, String hashKey);
?/*** Hash結構中屬性遞增** @param key     the key* @param hashKey the hash key* @param delta   the delta* @return the long*/Long hIncr(String key, String hashKey, Long delta);
?/*** Hash結構中屬性遞減** @param key     the key* @param hashKey the hash key* @param delta   the delta* @return the long*/Long hDecr(String key, String hashKey, Long delta);
?/*** 獲取Set結構** @param key the key* @return the set*/Set<Object> sMembers(String key);
?/*** 向Set結構中添加屬性** @param key    the key* @param values the values* @return the long*/Long sAdd(String key, Object... values);
?/*** 向Set結構中添加屬性** @param key    the key* @param time   the time* @param values the values* @return the long*/Long sAdd(String key, long time, Object... values);
?/*** 是否為Set中的屬性** @param key   the key* @param value the value* @return the boolean*/Boolean sIsMember(String key, Object value);
?/*** 獲取Set結構的長度** @param key the key* @return the long*/Long sSize(String key);
?/*** 刪除Set結構中的屬性** @param key    the key* @param values the values* @return the long*/Long sRemove(String key, Object... values);
?/*** 獲取List結構中的屬性** @param key   the key* @param start the start* @param end   the end* @return the list*/List<Object> lRange(String key, long start, long end);
?/*** 獲取List結構的長度** @param key the key* @return the long*/Long lSize(String key);
?/*** 根據索引獲取List中的屬性** @param key   the key* @param index the index* @return the object*/Object lIndex(String key, long index);
?/*** 向List結構中添加屬性** @param key   the key* @param value the value* @return the long*/Long lPush(String key, Object value);
?/*** 向List結構中添加屬性** @param key   the key* @param value the value* @param time  the time* @return the long*/Long lPush(String key, Object value, long time);
?/*** 向List結構中批量添加屬性** @param key    the key* @param values the values* @return the long*/Long lPushAll(String key, Object... values);
?/*** 向List結構中批量添加屬性** @param key    the key* @param time   the time* @param values the values* @return the long*/Long lPushAll(String key, Long time, Object... values);
?/*** 從List結構中移除屬性** @param key   the key* @param count the count* @param value the value* @return the long*/Long lRemove(String key, long count, Object value);
}

Service實現類

在UserService中,我們把用戶的信息存儲在Redis中。調用了RedisService的方法,同時給該鍵設置過期時間。大家在操作的時候,直接使用RedisService中的方法就可以了,這些方法還是挺全的。

package com.example.demo.service.impl;
?
import com.example.demo.entity.User;
import com.example.demo.service.RedisService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
?
/*** @program: SpringBoot-Redis-Demo* @description: 用戶服務實現類* @author: water76016* @create: 2020-12-29 09:24**/
@Service
public class UserServiceImpl implements UserService {@AutowiredRedisService redisService;
?@Value("${redis.database}")private String redisDatabase;@Value("${redis.key.user}")private String redisUserKey;@Value("${redis.expire.common}")private long expire;/*** 對用戶打招呼,返回user的toString()方法** @param user* @return*/@Overridepublic String helloUser(User user) {//設置鍵,鍵的格式為:數據庫名:user:用戶idString key = redisDatabase + ":" + redisUserKey + ":" + user.getId();//把用戶的toString,存在這個鍵里面redisService.set(key, user.toString());//設置鍵的過期時間redisService.expire(key, expire);return user.toString();}
}
package com.example.demo.service.impl;
?
import com.example.demo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
?
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
?
/*** @program: our-task* @description: redis操作服務接口實現類* @author: water76016* @create: 2020-09-24 16:45**/
@Service
public class RedisServiceImpl implements RedisService {/*** 由于沒有指定具體類型<String, Object>,用Resource注入才有效* */@Resourceprivate RedisTemplate redisTemplate;
?@Autowired(required = false)public void setRedisTemplate(RedisTemplate redisTemplate) {RedisSerializer stringSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringSerializer);redisTemplate.setValueSerializer(stringSerializer);redisTemplate.setHashKeySerializer(stringSerializer);redisTemplate.setHashValueSerializer(stringSerializer);this.redisTemplate = redisTemplate;}@Overridepublic void set(String key, Object value, long time) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);}
?@Overridepublic void set(String key, Object value) {
?redisTemplate.opsForValue().set(key, value);}
?@Overridepublic Object get(String key) {return redisTemplate.opsForValue().get(key);}
?@Overridepublic Boolean del(String key) {return redisTemplate.delete(key);}
?@Overridepublic Long del(List<String> keys) {return redisTemplate.delete(keys);}
?@Overridepublic Boolean expire(String key, long time) {return redisTemplate.expire(key, time, TimeUnit.SECONDS);}
?@Overridepublic Long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}
?@Overridepublic Boolean hasKey(String key) {return redisTemplate.hasKey(key);}
?@Overridepublic Long incr(String key, long delta) {return redisTemplate.opsForValue().increment(key, delta);}
?@Overridepublic Long decr(String key, long delta) {return redisTemplate.opsForValue().increment(key, -delta);}
?@Overridepublic Object hGet(String key, String hashKey) {return redisTemplate.opsForHash().get(key, hashKey);}
?@Overridepublic Boolean hSet(String key, String hashKey, Object value, long time) {redisTemplate.opsForHash().put(key, hashKey, value);return expire(key, time);}
?@Overridepublic void hSet(String key, String hashKey, Object value) {redisTemplate.opsForHash().put(key, hashKey, value);}
?@Overridepublic Map<Object, Object> hGetAll(String key) {return redisTemplate.opsForHash().entries(key);}
?@Overridepublic Boolean hSetAll(String key, Map<String, Object> map, long time) {redisTemplate.opsForHash().putAll(key, map);return expire(key, time);}
?@Overridepublic void hSetAll(String key, Map<String, Object> map) {redisTemplate.opsForHash().putAll(key, map);}
?@Overridepublic void hDel(String key, Object... hashKey) {redisTemplate.opsForHash().delete(key, hashKey);}
?@Overridepublic Boolean hHasKey(String key, String hashKey) {return redisTemplate.opsForHash().hasKey(key, hashKey);}
?@Overridepublic Long hIncr(String key, String hashKey, Long delta) {return redisTemplate.opsForHash().increment(key, hashKey, delta);}
?@Overridepublic Long hDecr(String key, String hashKey, Long delta) {return redisTemplate.opsForHash().increment(key, hashKey, -delta);}
?@Overridepublic Set<Object> sMembers(String key) {return redisTemplate.opsForSet().members(key);}
?@Overridepublic Long sAdd(String key, Object... values) {return redisTemplate.opsForSet().add(key, values);}
?@Overridepublic Long sAdd(String key, long time, Object... values) {Long count = redisTemplate.opsForSet().add(key, values);expire(key, time);return count;}
?@Overridepublic Boolean sIsMember(String key, Object value) {return redisTemplate.opsForSet().isMember(key, value);}
?@Overridepublic Long sSize(String key) {return redisTemplate.opsForSet().size(key);}
?@Overridepublic Long sRemove(String key, Object... values) {return redisTemplate.opsForSet().remove(key, values);}
?@Overridepublic List<Object> lRange(String key, long start, long end) {return redisTemplate.opsForList().range(key, start, end);}
?@Overridepublic Long lSize(String key) {return redisTemplate.opsForList().size(key);}
?@Overridepublic Object lIndex(String key, long index) {return redisTemplate.opsForList().index(key, index);}
?@Overridepublic Long lPush(String key, Object value) {return redisTemplate.opsForList().rightPush(key, value);}
?@Overridepublic Long lPush(String key, Object value, long time) {Long index = redisTemplate.opsForList().rightPush(key, value);expire(key, time);return index;}
?@Overridepublic Long lPushAll(String key, Object... values) {return redisTemplate.opsForList().rightPushAll(key, values);}
?@Overridepublic Long lPushAll(String key, Long time, Object... values) {Long count = redisTemplate.opsForList().rightPushAll(key, values);expire(key, time);return count;}
?@Overridepublic Long lRemove(String key, long count, Object value) {return redisTemplate.opsForList().remove(key, count, value);}
}

UserController控制器

接下來,我們新建一個controller包,在該包下新建UserController控制類。

package com.example.demo.controller;
?
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
?
/*** @program: SpringBoot-Redis-Demo* @description:* @author: water76016* @create: 2020-12-29 09:27**/
@RestController
@RequestMapping("/user")
public class UserController {@AutowiredUserService userService;
?@PostMapping("/helloUser")public String helloUser(@RequestBody User user){return userService.helloUser(user);}
?
}

結果測試

最后,我們啟動SpringBoot程序,程序運行在8080端口,在postman中進行測試。大家按照我在postman中的輸入,就會有相應的輸出了。

c3e6f8de8047a06e2ab765244dc3d7fd.png

另外,也來看看Redis中是否有相應的緩存結果。

26b6d1fd3b88867fa0813423528bd3e8.png

Demo地址

寫了這么多,還是擔心大家使用的時候有問題,所以我把該Demo放在了Github上,大家自行下載就可以了。

SpringBoot-Redis-Demo地址

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393734.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393734.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393734.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

linux課程設計qq,仿QQ聊天系統課程設計.doc

目錄緒論1一&#xff0e;需求分析11.1軟件功能需求分析21.2 安全需求分析2二&#xff0e;總體設計32.1 軟件結構圖32.2 功能描述32.2.1注冊功能概要42.2.2登錄功能概要42.2.3聊天功能概要52.3 安全設計6三&#xff0e;數據庫設計63.1概念結構設計63.2邏輯結構設計73.3物理結構設…

ocp linux 基礎要點

基本命令&#xff1a; 創建/修改/刪除用戶 useradd/usermod/userdel 創建/修改/刪除用戶組 groupadd/groupmod/groupdel 修改所屬用戶/所屬用戶組 chown/chgrp 修改權限 chmod 創建文件夾 mkdir 創建文件 touch 切換目錄 …

leetcode1386. 安排電影院座位(貪心)

如上圖所示&#xff0c;電影院的觀影廳中有 n 行座位&#xff0c;行編號從 1 到 n &#xff0c;且每一行內總共有 10 個座位&#xff0c;列編號從 1 到 10 。 給你數組 reservedSeats &#xff0c;包含所有已經被預約了的座位。比如說&#xff0c;researvedSeats[i][3,8] &…

首席技術執行官_如何在幾分鐘內找到任何首席執行官的電子郵件地址

首席技術執行官by Theo Strauss由西奧斯特勞斯(Theo Strauss) 如何在幾分鐘內找到任何首席執行官的電子郵件地址 (How to find any CEO’s email address in minutes) 銀河電子郵件指南&#xff1a;第一部分 (The Emailer’s Guide To The Galaxy: Part I) I’m 17, so my net…

Linux 查看磁盤或文件夾及文件大小

當磁盤大小超過標準時會有報警提示&#xff0c;這時如果掌握df和du命令是非常明智的選擇。 df可以查看一級文件夾大小、使用比例、檔案系統及其掛入點&#xff0c;但對文件卻無能為力。 du可以查看文件及文件夾的大小。 兩者配合使用&#xff0c;非常有效。比如用df查看哪個…

Python列表基礎

列表&#xff1a;創建列表:list[] 注意&#xff1a;列表里面類型可以是不同的類型 取值&#xff1a;list[2]   替換&#xff1a;注意不要越界(下表超出了可表示范圍) 操作&#xff1a; 合并列表&#xff1a;   list3list2list1 列表的重復:   (list8*3)   判斷元素是否…

樹莓派 觸摸屏_如何用樹莓派搭建一個顆粒物(PM2.5)傳感器

用樹莓派、一個廉價的傳感器和一個便宜的屏幕監測空氣質量。-- Stephan Tetzel(作者)大約一年前&#xff0c;我寫了一篇關于如何使用樹莓派和廉價傳感器測量 空氣質量 的文章。我們這幾年已在學校里和私下使用了這個項目。然而它有一個缺點&#xff1a;由于它基于無線/有線網&a…

shell 25個常用命令

1.列出所有目錄使用量&#xff0c;并按大小排序。 ls|xargs du -h|sort -rn #不遞歸下級目錄使用du -sh2.查看文件排除以#開關和空白行&#xff0c;適合查看配置文件。 egrep -v "^#|^$" filenamesed /#.*$/d; /^ *$/d3.刪除空格和空行。 sed /^$/d filename #刪除空…

tensorflow入門_TensorFlow法律和統計入門

tensorflow入門by Daniel Deutsch由Daniel Deutsch TensorFlow法律和統計入門 (Get started with TensorFlow on law and statistics) What this is about 這是關于什么的 What we will use 我們將使用什么 Get started 開始吧 Shell commands for installing everything you …

centos7 nginx+php5.6+mysql安裝與配置

安裝與配置 php 56的安裝 php的配置寫在 php.ini&#xff0c;可在phpinfo()中查看 //查找已安裝 yum list installed | grep php // php卸載 yum -y remove php56* yum remove httpd* php* 可用的資源&#xff1a;centos 安裝php56nginx nginx php-fpm nginx安裝 sudo rpm -Uv…

leetcode337. 打家劫舍 III(dfs)

在上次打劫完一條街道之后和一圈房屋后&#xff0c;小偷又發現了一個新的可行竊的地區。這個地區只有一個入口&#xff0c;我們稱之為“根”。 除了“根”之外&#xff0c;每棟房子有且只有一個“父“房子與之相連。一番偵察之后&#xff0c;聰明的小偷意識到“這個地方的所有房…

c語言面試題東軟,2012東軟筆試題

1、下列變量定義錯誤的是&#xff24;int a;double b4.5;boolean btrue;float f9.8; (9.8f)2、65%32的值是 D 3%53219103、對于一個三位的正整數 n&#xff0c;取出它的十位數字k(k為整型)的表達式是k n / 10 % 10k ( n - n / 100 * 100 )k n % 10k n / 104、下列語句序列執…

matlab肌電信號平滑濾波_MATLAB圖像處理:43:用高斯平滑濾波器處理圖像

本示例說明了如何使用imgaussfilt來對圖像應用不同的高斯平滑濾波器。高斯平滑濾波器通常用于降低噪聲。將圖像讀入工作區。I imread(cameraman.tif);使用各向同性的高斯平滑核增加標準偏差來過濾圖像。高斯濾波器通常是各向同性的&#xff0c;也就是說&#xff0c;它們在兩個…

Github 簡明教程 - 添加遠程庫

現在的情景是&#xff0c;你已經在本地創建了一個Git倉庫后&#xff0c;又想在GitHub創建一個Git倉庫&#xff0c;并且讓這兩個倉庫進行遠程同步&#xff0c;這樣&#xff0c;GitHub上的倉庫既可以作為備份&#xff0c;又可以讓其他人通過該倉庫來協作&#xff0c;真是一舉多得…

githooks_使用Githooks改善團隊的開發工作流程

githooksby Daniel Deutsch由Daniel Deutsch 使用Githooks改善團隊的開發工作流程 (Improve your team’s development workflow with Githooks) Every product that is developed by more than one programmer needs to have some guidelines to harmonize the workflow.由多…

分享AI有道干貨 | 126 篇 AI 原創文章精選(ML、DL、資源、教程)

一年多來&#xff0c;公眾號【AI有道】已經發布了 140 的原創文章了。內容涉及林軒田機器學習課程筆記、吳恩達 deeplearning.ai 課程筆記、機器學習、深度學習、筆試面試題、資源教程等等。值得一提的是每篇文章都是我用心整理的&#xff0c;編者一貫堅持使用通俗形象的語言給…

c語言qt生成dll與加載dll,Qt制作界面的DLL以及調用

1、將界面做成dll修改pro文件DEFINES WIDGETDLL_LIBRARYTEMPLATE lib修改頭文件#if defined(WIDGETDLL_LIBRARY)# define WIDGETDLLSHARED_EXPORT Q_DECL_EXPORT#else# define WIDGETDLLSHARED_EXPORT Q_DECL_IMPORT#endifclass WIDGETDLLSHARED_EXPORT WidgetDll:public QWi…

leetcode1338. 數組大小減半(貪心算法)

給你一個整數數組 arr。你可以從中選出一個整數集合&#xff0c;并刪除這些整數在數組中的每次出現。 返回 至少 能刪除數組中的一半整數的整數集合的最小大小。 示例 1&#xff1a; 輸入&#xff1a;arr [3,3,3,3,5,5,5,2,2,7] 輸出&#xff1a;2 解釋&#xff1a;選擇 {3…

20162329 張旭升 2017 - 2018 《程序設計與數據結構》第五周總結

20162329 2017-2018-1 《程序設計與數據結構》第五周學習總結 教材學習內容總結 1.學習目標 了解集合的概念了解并使用抽象數據類型初步了解使用Java泛型學習棧這種數據結構用數組、鏈表實現棧2.學習內容 集合的概念&#xff1a; 集合是手機并組織其他對象的對象&#xff0c;他…

centos 安裝trace_前期的準備工作-MacOS Mojave 10.14.3 下安裝CentOS 7及Bochs 002

MacOS Mojave 10.14.3 下使用虛擬機安裝CentOS 7 以及 Bochs 2.6.9CentOS 7.6.1810 系統下 安裝Bochs 2.6.91 下載CentOS 7.6.1810網址為https://www.centos.org/遇到的問題安裝后無法使用使用網絡&#xff0c;最簡單的解決方法就是增加一個新的網絡適配器&#xff0c;使用Nat共…