Redis的Java客戶端

来源:https://www.cnblogs.com/lcha-coding/archive/2022/05/30/16327868.html
-Advertisement-
Play Games

- Jedis - 優點:以 Redis 命令作為方法名稱,學習成本低廉,簡單且實用 - 缺點:Jedis 的實例是線程不安全的,在多線程的環境下需要基於線程池來使用 - lettuce(spring 官方預設) - 基於 Netty 實現的,支持同步、非同步和響應式編程方式,並且是線程安... ...


Redis 的 Java 客戶端

  • Jedis
    • 優點:以 Redis 命令作為方法名稱,學習成本低廉,簡單且實用
    • 缺點:Jedis 的實例是線程不安全的,在多線程的環境下需要基於線程池來使用
  • lettuce(spring 官方預設)
    • 基於 Netty 實現的,支持同步、非同步和響應式編程方式,並且是線程安全的。支持 Redis 的哨兵模式、集群模式、管道模式
  • Redisson(適用於分散式的環境)
    • 基於 Redis 實現的分散式、可伸縮的 Java 數據結構的集合。包含 Map、Queue、Lock、Semaphore、AtomicLong等強大的功能

Jedis

Jedis 基本使用步驟

  1. 引入依賴
  2. 創建Jedis對象,建立連接
  3. 使用Jedis,方法名與Redis命令一致
  4. 釋放資源

測試 Jedis 相關方法

如果 @BeforeEach報錯,記得在 pom 文件裡面引入 Junit API 包的依賴

<!-- junit-jupiter-api -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
</dependency>

(這裡以 String 和 Hash 兩種類型為例)

package com.lcha.test;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import java.util.Map;

public class JedisTest {

    private Jedis jedis;

    @BeforeEach
    void setUp(){
        //1.建立連接
        jedis = new Jedis("xxxxxxxxxx",6379);
        //2.設置密碼
        jedis.auth("xxxxxxxxx");
        //3.選擇庫
        jedis.select(0);
    }

    @Test
    void testStr(){
        //4.存入數據
        String result = jedis.set("name", "胡歌");
        System.out.println("result = " + result);
        //5.獲取數據
        String name = jedis.get("name");
        System.out.println("name = " + name);
    }

    @Test
    void testHash(){
        jedis.hset("user:1","name","Jack");
        jedis.hset("user:1","age","21");

        Map<String, String> map = jedis.hgetAll("user:1");
        System.out.println(map);
    }

    @AfterEach
    void tearDown(){
        //6.釋放連接
        if(jedis != null){
            jedis.close();
        }
    }
}

Jedis連接池

Jedis本身是線程不安全的,並且頻繁的創建和銷毀連接會有性能損耗,因此我們推薦大家使用Jedis連接池代替Jedis的直連方式。

首先創建一個 Jedis 連接池工具類

package com.lcha.jedis.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisConnectionFactory {
    private static final JedisPool jedisPool;

    static {
        //配置連接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(8);  //最大連接數:8
        poolConfig.setMaxIdle(8);   //最大空閑連接
        poolConfig.setMinIdle(0);
        poolConfig.setMaxWaitMillis(1000);
        //創建連接池對象
        jedisPool = new JedisPool(poolConfig,"xxxx",6379,
                1000,"xxxx");
    }

    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}

更改之前 Jedis 的連接方式,採用連接池連接的方式

package com.lcha.test;

import com.lcha.jedis.util.JedisConnectionFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import java.util.Map;

public class JedisTest {

    private Jedis jedis;

    @BeforeEach
    void setUp(){
        //1.建立連接
        //jedis = new Jedis("xxxx",6379);
        jedis = JedisConnectionFactory.getJedis();
        //2.設置密碼
        jedis.auth("xxxx");
        //3.選擇庫
        jedis.select(0);
    }

    @Test
    void testStr(){
        //4.存入數據
        String result = jedis.set("name", "胡歌");
        System.out.println("result = " + result);
        //5.獲取數據
        String name = jedis.get("name");
        System.out.println("name = " + name);
    }

    @Test
    void testHash(){
        jedis.hset("user:1","name","Jack");
        jedis.hset("user:1","age","21");

        Map<String, String> map = jedis.hgetAll("user:1");
        System.out.println(map);
    }

    @AfterEach
    void tearDown(){
        if(jedis != null){
            jedis.close();
        }
    }
}

註意:當使用連接池連接時,代碼最後的 if(jedis != null){jedis.close();}不會真正的銷毀連接,而是將本連接歸還到連接池中

源碼如下:

public void close() {
        if (this.dataSource != null) {
            Pool<Jedis> pool = this.dataSource;
            this.dataSource = null;
            if (this.isBroken()) {
                pool.returnBrokenResource(this);
            } else {
                pool.returnResource(this); //註意這裡!!!!
            }
        } else {
            this.connection.close();
        }

    }

SpringDataRedis

SpringData是Spring中數據操作的模塊,包含對各種資料庫的集成,其中對Redis的集成模塊就叫做SpringDataRedis

官網地址:https://spring.io/projects/spring-data-redis

  • 提供了對不同Redis客戶端的整合(Lettuce和Jedis)
  • 提供了RedisTemplate統一API來操作Redis
  • 支持Redis的發佈訂閱模型
  • 支持Redis哨兵和Redis集群
  • 支持基於Lettuce的響應式編程
  • 支持基於JDK、JSON、字元串、Spring對象的數據序列化及反序列化
  • 支持基於Redis的JDKCollection實現

RedisTemplate 工具類

API 返回值類型 說明
RedisTemplate.opsForValue() ValueOperations 操作 String 類型數據
RedisTemplate.opsForHash() HashOperations 操作 Hash 類型數據
RedisTemplate.opsForList() ListOperations 操作 List 類型數據
RedisTemplate.opsForSet() SetOperations 操作 Set 類型數據
RedisTemplate.opsForZSet() ZSetOperations 操作 SortedSort 類型數據
RedisTemplate 通用命令

使用步驟

  1. 引入 spring-boot-starter-data-redis 依賴

    <!-- redis依賴 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <!-- common-pool -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
            </dependency>
    
  2. 在 application.yml 文件中配置 Redis 信息

    spring:
      redis:
        host: xxxx
        port: 6379
        password: xxxx
        lettuce:
          pool:
            max-active: 8
            max-idle: 8
            min-idle: 0
            max-wait: 100ms
    
  3. 註入 RedisTemplate 並使用

package com.lcha;

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.RedisTemplate;

@SpringBootTest
class RedisDemoApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void testString() {
        //寫入一條String數據
        redisTemplate.opsForValue().set("name", "胡歌");
        //獲取string數據
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name = " + name);
    }

}

序列化問題

RedisTemplate可以接收任意Object作為值寫入Redis,只不過寫入前會把Object序列化為位元組形式,預設是採用JDK序列化,得到的結果是這樣的:

缺點:

  1. 可讀性差
  2. 記憶體占用較大

解決方法:改變序列化器

自定義 RedisTemplate 序列化方式

package com.lcha.redis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        //創建 RedisTemplate 對象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //設置連接工廠
        template.setConnectionFactory(connectionFactory);
        //創建 JSON 序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //設置 Key 的序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        //設置 Value 的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        //返回
        return template;
    }
}

重新運行剛纔的代碼,結果如下圖所示:

存儲對象數據時也是一樣的

  1. 創建一個對象類

    package com.lcha.redis.pojo;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
        private String name;
        private Integer age;
    }
    
  2. 編寫測試方法

  3. 	@Test
        void testSaveUser(){
            redisTemplate.opsForValue().set("user:100", new User("胡歌",21));
            User o = (User) redisTemplate.opsForValue().get("user:100");
            System.out.println("o = " + o);
        }
    
  4. 列印結果

JSON方式依然存在的缺陷

儘管 JSON 的序列化方式可以滿足我們的需求,但是依然存在一些問題。

為了在反序列化時知道對象的類型,JSON序列化器會將類的class類型寫入json結果中,存入Redis,會帶來額外的記憶體開銷。

如何解決

為了節省記憶體空間,我們並不會使用JSON序列化器來處理value,而是統一使用String序列化器,要求只能存儲String類型的key和value。當需要存儲Java對象時,手動完成對象的序列化和反序列化。

  1. 直接使用 StringRedisTemplate 即可

    package com.lcha;
    
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.lcha.redis.pojo.User;
    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.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    
    @SpringBootTest
    class RedisStringTests {
    
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
    
        @Test
        void testString() {
            //寫入一條String數據
            stringRedisTemplate.opsForValue().set("name", "胡歌");
            //獲取string數據
            Object name = stringRedisTemplate.opsForValue().get("name");
            System.out.println("name = " + name);
        }
    
        private static final ObjectMapper mapper = new ObjectMapper();
    
        @Test
        void testSaveUser() throws JsonProcessingException {
            //創建對象
            User user = new User("虎哥",21);
            //手動序列化
            String json = mapper.writeValueAsString(user);
            //寫入數據
            stringRedisTemplate.opsForValue().set("user:200", json);
            //獲取數據
            String jsonUser = stringRedisTemplate.opsForValue().get("user:200");
            User user1 = mapper.readValue(jsonUser, User.class);
            System.out.println("user1 = " + user1);
        }
    
    }
    
  2. 結果如下

對 Hash 類型的操作

  1. 編寫方法

    @Test
        void testHash(){
            stringRedisTemplate.opsForHash().put("user:300", "name", "張三");
            stringRedisTemplate.opsForHash().put("user:300", "age", "18");
    
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:300");
            System.out.println("entries = " + entries);
    
        }
    
  2. 結果如下


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

-Advertisement-
Play Games
更多相關文章
  • 網路安全滲透(WIFI) By:edolf 時間:21-12-8 簡介:這是一篇關於無線網路的(WIFI)的滲透教程 理解基礎 關於路由器 無線路由發展標準歷史 協議標準 發佈時間 頻段 描述 802.11 1999 2.4GHz 定義微波和紅外線的物理層和MAC子層 802.11a 1999-09 ...
  • 鏡像下載、功能變數名稱解析、時間同步請點擊 阿裡雲開源鏡像站 由於AI_Station 是使用容器構建環境的,而且只提供鏡像上傳下載功能,不為容易提供網路功能,因此需要在平臺上把鏡像拉取到本地,並安裝一些必備軟體然後再打包成鏡像上傳回去,因此需要在本地構建docker環境,於是如下: 安裝GPG證書 cur ...
  • 本文例子參考《STM32單片機開發實例——基於Proteus虛擬模擬與HAL/LL庫》 源代碼:https://github.com/LanLinnet/STM33F103R6 項目要求 掌握SPI匯流排通信規則,使用單片機每隔1s讀取一次溫度感測器TC72的溫度值,並通過串口將讀取的溫度值發送出去。 ...
  • 鏡像下載、功能變數名稱解析、時間同步請點擊 阿裡雲開源鏡像站 概述 VMware Workstation Pro 是行業標準桌面 Hypervisor(虛擬化技術),使用它可在 Windows 或 Linux 桌面上運行 Windows、Linux 和 BSD 虛擬機。 什麼意思呢? VMware Work ...
  • firewalld 1、firewalld firewalld防火牆是centos7系統預設的防火牆管理工具取代了之前的iptables防火牆 工作在網路層、屬於包括過濾防火牆 firewalld和iptables都是用來管理防火牆的工具(屬於用戶狀態)來定義防火牆的各種規則功能 內部結構都指向ne ...
  • 痞子衡嵌入式半月刊: 第 55 期 這裡分享嵌入式領域有用有趣的項目/工具以及一些熱點新聞,農曆年分二十四節氣,希望在每個交節之日準時發佈一期。 本期刊是開源項目(GitHub: JayHeng/pzh-mcu-bi-weekly),歡迎提交 issue,投稿或推薦你知道的嵌入式那些事兒。 上期回顧 ...
  • 一、PL/SQL簡介 1)SQL是一種標準化的結構化查詢語言,在資料庫領域有著廣泛的應用和重大影響。但是SQL並不能完成一個過程所能完成的任務,如某一個條件成立進行數據插入,否則不進行數據插入。 2)PL/SQL是Oracle公司對SQL語言的擴展,全面支持所有的SQL操作與數據類型。 3)PL/S ...
  • ClickHouse的由來 ClickHouse是什麼資料庫?ClickHouse速度有多快?應用場景是怎麼樣的?ClickHouse是關係型資料庫嗎?ClickHouse目前是很火爆的一款面向OLAP的數據,可以提供秒級的大數據查詢。 Google於2003~2006年相繼發表了三篇論文“Goog ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...