8、Redis-Jedis、Lettuce和一個Demo

目錄

一、Jedis

二、Lettuce

三、一個Demo


Java集成Redis主要有3個方案:Jedis、Lettuce和Redisson。

其中,Jedis、Lettuce側重于單例Redis,而Redisson側重于分布式服務。

項目資源在文末


一、Jedis

1、創建SpringBoot項目

2、引入依賴

其中,jedis是所需要的依賴,lombok是為了方便后續配置

        <dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

3、 配置yml

#redis配置--jedis版
jedis:pool:#redis服務器的IPhost: localhost#redis服務器的Portport: 6379#數據庫密碼password:#連接超時時間timeout: 7200#最大活動對象數maxTotall: 100#最大能夠保持idel狀態的對象數maxIdle: 100#最小能夠保持idel狀態的對象數minIdle: 50#當池內沒有返回對象時,最大等待時間maxWaitMillis: 10000#當調用borrow Object方法時,是否進行有效性檢查testOnBorrow: true#當調用return Object方法時,是否進行有效性檢查testOnReturn: true#“空閑鏈接”檢測線程,檢測的周期,毫秒數。如果為負值,表示不運行“檢測線程”。默認為-1.timeBetweenEvictionRunsMillis: 30000#向調用者輸出“鏈接”對象時,是否檢測它的空閑超時;testWhileIdle: true# 對于“空閑鏈接”檢測線程而言,每次檢測的鏈接資源的個數。默認為3.numTestsPerEvictionRun: 50

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

4、導入配置文件和加載配置類

導入配置文件:JedisProperties,導入yml文件內容

加載配置類:JedisConfig,加載JedisProperties內容

①JedisProperties

package com.example.redis_java.config;import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "jedis.pool")
@Getter
@Setter
public class JedisProperties {private int maxTotall;private int maxIdle;private int minIdle;private int maxWaitMillis;private boolean testOnBorrow;private boolean testOnReturn;private int timeBetweenEvictionRunsMillis;private boolean testWhileIdle;private int numTestsPerEvictionRun;private String host;private String password;private int port;private int timeout;
}

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

②JedisConfig

說明:如果SpringBoot是2.x版本,JedisConfig請使用注釋掉的兩行代碼而不是它們對應的上面的代碼

package com.example.redis_java.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;import java.time.Duration;@Configuration
public class JedisConfig {/*** jedis連接池** @param jedisProperties* @return*/@Beanpublic JedisPool jedisPool(JedisProperties jedisProperties) {JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(jedisProperties.getMaxTotall());config.setMaxIdle(jedisProperties.getMaxIdle());config.setMinIdle(jedisProperties.getMinIdle());config.setMaxWait(Duration.ofMillis(jedisProperties.getMaxWaitMillis()));// config.setMaxWaitMillis(jedisProperties.getMaxWaitMillis());config.setTestOnBorrow(jedisProperties.isTestOnBorrow());config.setTestOnReturn(jedisProperties.isTestOnReturn());config.setTimeBetweenEvictionRuns(Duration.ofMillis(jedisProperties.getTimeBetweenEvictionRunsMillis()));// config.setTimeBetweenEvictionRunsMillis(jedisProperties.getTimeBetweenEvictionRunsMillis());config.setTestWhileIdle(jedisProperties.isTestWhileIdle());config.setNumTestsPerEvictionRun(jedisProperties.getNumTestsPerEvictionRun());if (StringUtils.hasText(jedisProperties.getPassword())) {return new JedisPool(config, jedisProperties.getHost(), jedisProperties.getPort(), jedisProperties.getTimeout(), jedisProperties.getPassword());}return new JedisPool(config, jedisProperties.getHost(), jedisProperties.getPort(), jedisProperties.getTimeout());}
}

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

③項目結構

5、測試

①測試前

②測試類

package com.example.redis_java;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;@SpringBootTest
public class JedisTest {@Autowiredprivate JedisPool jedisPool;@Testpublic void testConnection() {System.out.println(jedisPool);Jedis jedis = jedisPool.getResource();jedis.set("name", "Trxcx");System.out.println(jedis.get("name"));jedis.sadd("mySet", "a", "b", "d");System.out.println(jedis.smembers("mySet"));// jedis的方法名就是redis的命令jedis.close();}
}

③項目結構

??

④運行測試類

⑤測試后

說明:jedis的方法名就是redis的命令。如sadd、smembers。


二、Lettuce

Lettuce配置比較簡單,這里直接在上一個項目的基礎上進行配置,新項目配置Lettuce方法一致。

1、引入依賴

        <!--Lettuce依賴--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>

2、配置yml

如果有密碼,設置對應的密碼。

spring:redis:host: 127.0.0.1port: 6379# password: admin

3、測試

①編寫測試類

package com.example.redis_java;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;@SpringBootTest
public class LettureTest {@Autowiredprivate StringRedisTemplate template;// 約定:// 操作redis的key是字符串// value是字符串類型或字符串類型元素@Testpublic void testRedis() {template.opsForValue().set("name", "Trxcx");System.out.println(template.opsForValue().get("name"));template.opsForSet().add("Games","RDR2","CS2","ACOd");System.out.println(template.opsForSet().members("Games"));// 操作string// template.opsForValue().xx();// 操作hash// template.opsForHash().xx();// 操作list// template.opsForList().xx();// 操作set// template.opsForSet().xx();// 操作zset// template.opsForZSet().xx();// spring-data-redis方法是redis命令全稱// template.opsForList().rightPush()  //rpush// 全局命令在template類上// template.keys("*");}
}

②項目結構

③運行測試類

4、說明:

①Lettuce使用StringRedisTemplate的一個對象完成對Redis的操作,不存在像Jedis那樣獲取Redis資源使用完再關閉的情況。

②Lettuce通過opsForxxx完成對不同value類型的操作,例如

  • opsForValue()是操作String類型的
  • opsForHash()是操作Hash類型的
  • opsForList()是操作List類型的
  • opsForSet()是操作Set類型的
  • opsForZSet()是操作Zset類型的

③Lettuce的方法名是Redis命令的全稱

例如:template.opsForList().rightPush(),對應Redis中的rpush命令

④全局命令作用在StringRedisTemplate對象上

例如:template.keys("*");


三、一個Demo

這個demo實現了每次刷新或者訪問網頁時,閱讀量+1的效果。

啟動SpringBoot項目后,訪問http://localhost:8080/detail.html,每次刷新頁面閱讀量+1。?


項目資源鏈接:

1、【免費】Redis-Java.zip資源-CSDN文庫

2、【免費】RedisDemo.zip資源-CSDN文庫?

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

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

相關文章

電商小程序10分類管理

目錄 1 分類數據源2 搭建功能3 創建變量讀取數據4 綁定數據總結 本篇我們介紹一下電商小程序的分類管理功能的開發&#xff0c;先看我們的原型圖&#xff1a; 在首頁我們是展示了四個分類的內容&#xff0c;采用上邊是圖標&#xff0c;下邊是文字的形式。使用低代碼開發&#…

【系統分析師】-需求工程

一、需求工程 需求工程分為需求開發和需求管理。 需求開發&#xff1a;需求獲取&#xff0c;需求分析&#xff0c;需求定義、需求驗證。 需求管理&#xff1a;變更控制、版本控制、需求跟蹤&#xff0c;需求狀態跟蹤。&#xff08;對需求基線的管理&#xff09; 1.1需求獲取…

MySQL:合并查詢語句

1、查詢表的數據 t_book表數據 SELECT * FROM db_book.t_book; t_booktype表數據 SELECT * FROM db_book.t_booktype; 提醒&#xff1a; 下面的查詢操作的數據來自上圖查詢表的數據 2. 使用 UNION 查詢結果合并&#xff0c;會去掉重復的數據 使用UNION關鍵字是&#xff0c;數…

社區店經營口號大揭秘:如何吸引更多顧客?

社區店的經營口號是吸引顧客的重要工具&#xff0c;一個好的口號能夠在短時間內傳達店鋪的特色和價值&#xff0c;并引起顧客的興趣。 作為一名開鮮奶吧5年的創業者&#xff0c;我將分享一些關于社區店經營口號的干貨&#xff0c;幫助你吸引更多的顧客。 1、突出獨特賣點&…

群控代理IP搭建教程:打造一流的網絡爬蟲

目錄 前言 一、什么是群控代理IP&#xff1f; 二、搭建群控代理IP的步驟 1. 獲取代理IP資源 2. 配置代理IP池 3. 選擇代理IP策略 4. 編寫代理IP設置代碼 5. 異常處理 三、總結 前言 群控代理IP是一種常用于網絡爬蟲的技術&#xff0c;通過使用多個代理IP實現并發請求…

優思學院|3步驟計算出Cpk|學習Minitab

在生產和質量管理中&#xff0c;準確了解和控制產品特性至關重要。一個關鍵的工具是Cpk值&#xff0c;它是衡量生產過程能力的重要指標。假設我們有一個產品特性的規格是5.080.02&#xff0c;通過收集和分析過程數據&#xff0c;我們可以計算出Cpk值&#xff0c;進而了解生產過…

CentOS 定時調度

文章目錄 一、場景說明二、腳本職責三、參數說明四、操作示例五、注意事項 一、場景說明 本自動化腳本旨在為提高研發、測試、運維快速部署應用環境而編寫。 腳本遵循拿來即用的原則快速完成 CentOS 系統各應用環境部署工作。 統一研發、測試、生產環境的部署模式、部署結構、…

Java中靈活使用Mockito

目錄 Java中靈活使用Mockito引言Mockito簡介基本用法實例演示使用場景和案例解決方案結語 Java中靈活使用Mockito 引言 Mockito是Java中常用的mock框架之一&#xff0c;用于進行單元測試時模擬對象的行為。本文將介紹Mockito的基本用法&#xff0c;并探討如何在實際項目中靈活…

AP8P059 PIR 人體感應太陽能 LED 燈控制芯片

概述 AP8P059 是一款集成低壓 LDO、光控、充電控制、過充保護、欠壓保護、PIR感應、延時為一體的人體感應太陽能 LED燈控制芯片&#xff0c;只需要很少的外接元件&#xff0c;適用于鋰電池供電的PIR人體感應LED燈具的應用。外置的一級帶通增益放大器便于客戶調整感應靈敏度&am…

QT MinGW64編譯vlc源碼

編譯環境搭建 參考文章《QT Mingw32/64編譯ffmpeg源碼生成32/64bit庫以及測試》&#xff0c;搭建msys64環境&#xff1b; 運行msys.exe,運行&#xff1a; pacman -S git subversion cvs automake autoconf libtool m4 make gettext pkg-config mingw-w64-i686-lua findutils …

docker配置數據默認存儲路徑graph已過時,新版本中是data-root

錯誤信息 我在修改/etc/docker/daemon.json文件中&#xff0c;添加存儲路徑graph字段。然后sudo systemctl restart docker包如下錯誤&#xff1a;使用journalctl -xeu docker.service錯誤信息&#xff0c;發現不能匹配graph字段。 原因 我的docker版本&#xff1a; 在doc…

mybatisplus整合flowable-ui-modeler報錯

1、問題 Description:file [/Users/xingyuwei/Documents/project/java/springboot_01/target/classes/com/xingyu/mapper/TemplateMapper.class] required a single bean, but 2 were found:- sqlSessionFactory: defined by method sqlSessionFactory in class path resource…

TypeScript08:在TS中使用模塊化

前言&#xff1a;tsconfig.json中的配置 一、前端領域中的模塊化標準 前端領域中的模塊化標準有&#xff1a; ES6、commonjs、amd、umd、system、esnext 二、 TS中如何書寫模塊化語句 TS 中&#xff0c;導入和導出模塊&#xff0c;統一使用 ES6 的模塊化標準。 myModule.ts &a…

Keil新版本安裝編譯器ARMCompiler 5.06

0x00 緣起 我手頭的項目在使用最新版本的編譯器后&#xff0c;燒錄后無法正常運行&#xff0c;故安裝5.06&#xff0c;測試后發現程序運行正常&#xff0c;以下為編譯器的安裝步驟。 0x01 解決方法 1. 下載編譯器安裝文件&#xff0c;可以去ARM官網下載&#xff0c;也可以使用我…

藍橋杯練習系統(算法訓練)ALGO-993 RP大冒險

資源限制 內存限制&#xff1a;64.0MB C/C時間限制&#xff1a;200ms Java時間限制&#xff1a;600ms Python時間限制&#xff1a;1.0s 問題描述 請盡情使用各種各樣的函數來測試你的RP吧~~~ 輸入格式 一個數N表示測點編號。 輸出格式 一個0~9的數。 樣例輸入 0 樣…

【airtest】自動化入門教程(三)Poco操作

目錄 一、準備工作 1、創建一個pthon腳本 2、光標位置 2、選擇Android 3、選擇yes 二、定位元素 三、poco基于設備/屏幕 方式 1、poco.click( (x,y))基于屏幕點擊相對坐標為x&#xff0c;y的位置 2、poco.get_screen_size() 3、poco.swipe(v1,v2)基于屏幕從v1位置滑到…

02.剛性事務

剛性事務 1.DTP模型 X/Open組織介紹 X/OPEN是一個組織&#xff08;現在的open group&#xff09;X/Open國際聯盟有限公司是一個歐洲基金會&#xff0c;它的建立是為了向UNIX環境提供標準。它主要的目標是促進對UNIX語言、接口、網絡和應用的開放式系統協議的制定。它還促進在…

初識C語言—常見關鍵字

變量的命名最好有意義 名字必須是字母&#xff0c;數字&#xff0c;下劃線組成&#xff0c;不能有特殊字符&#xff0c;同時不能以數字開頭 變量名不能是關鍵字 typedef---類型定義&#xff0c;類型重命名 #include <stdio.h>typedef unsigned int uint; //將unsigne…

ubuntu20.04設置docker容器開機自啟動

ubuntu20.04設置docker容器開機自啟動 1 docker自動啟動2 容器設置自動啟動3 容器自啟動失敗處理 1 docker自動啟動 &#xff08;1&#xff09;查看已啟動的服務 $ sudo systemctl list-units --typeservice此命令會列出所有當前加載的服務單元。默認情況下&#xff0c;此命令…

龍蜥Anolis 8.4 安裝 salt-stack

Python3 安裝 sudo dnf install python3 -y Install SaltStack Yum Repository sudo dnf install -y https://repo.saltstack.com/py3/redhat/salt-py3-repo-latest.el8.noarch.rpm sudo dnf makecache sudo dnf -y update 安裝Salt-stack sudo dnf install -y salt-master …