Spring Boot 整合Jedis連接Redis和簡單使用


摘要:首先介紹如何在Windows系統安裝Redis環境,然后在Spring Boot 項目中集成 Redis,最后簡單地做了一個使用Jedis操作redis連接池的測試用例。

§准備Redis環境

  這里介紹如何在 windows 10 系統安裝 Redis 5.0.10,希望對沒有接觸過Redis或剛接觸Redis的小伙伴有些許幫助。如果已經安裝Redis,請跳過本節。安裝包下載地址: https://github.com/tporadowski/redis/releases

  安裝Redis。下載安裝包后右鍵解壓到硬盤某個目錄下,我安裝的是64位Redis,放在了目錄C:\Program Files\redis中:

  啟動Redis。在命令行窗口進入redis目錄后,執行如下命令開啟服務:

redis-server.exe redis.windows.conf

  注意加上redis.windows.conf。這個窗口要保持開啟,關閉時redis服務會自動關閉。

  另外開啟一個命令行窗口,進入redis目錄下后執行如下命令:

redis-cli.exe -h 127.0.0.1 -p 6379

  IP地址127.0.0.1為redis服務所部署服務器的IP地址。因為是本機安裝,故直接使用127.0.0.1啟動。Redis默認端口是6379,可以通過編輯文件 redis.windows.conf 修改里面的端口號。

  如果redis設置了密碼,可以添加參數-a指定密碼,例如:

redis-cli.exe -h 127.0.0.1 -p 6379 -a yourPassword

  向Redis設置鍵值對:

set myKey abc

  取出鍵值對:

get myKey

  在《使用批處理腳本在win10系統啟動Redis 5.0.10》中,小編介紹了如何快速使用批處理文件啟動Redis,需要的小伙伴趕快去圍觀吧!

  至此,安裝、啟動和測試完畢。主要就是按照參考文獻[1]操作一遍,如果需要在Linux環境安裝,就去參考文獻[1]瞧瞧吧!

  Redis服務器連接密碼默認為空,可以通過在控制台執行命令 auth yourPassword設置密碼,其中,yourPassword為你自己的密碼,自行更改,設置成功時Redis返回字符串 OK。

§Spring Boot項目集成Redis

  所用軟件開發環境如下:

  ♦ java version 13.0.1
  ♦ IntelliJ IDEA 2019.3.2 (Ultimate Edition)
  ♦ Spring Boot 2.3.0.RELEASE
  ♦Redis 5.0.10

  添加Redis依賴:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.1.0</version>
</dependency>

  Jedis為我們提供了多種操作Redis的方式:單機單連接方式、單機連接池方式和多機分布式+連接池方式。這里演示使用單個Redis實例的單機連接池方式。在application.properties中新增Jedis的相關配置:

spring.redis.host=127.0.0.1
spring.redis.database=0
spring.redis.port=6379
# 我的redis沒有設置密碼,故缺省密碼
spring.redis.password=
# 連接超時時間,單位 ms(毫秒)
spring.redis.timeout=3200
# 連接池中的最大空閑連接,默認值也是8
spring.redis.jedis.pool.max-idle=10
#連接池中的最小空閑連接,默認值也是0
spring.redis.jedis.pool.min-idle=3
# 連接池最大jedis實例個數,如果賦值為-1,則表示不限制;pool如果已經全部分配,則狀態變為exhausted(耗盡)。
spring.redis.jedis.pool.max-active=210
# 可用連接的最大等待時間,單位毫秒,默認值為-1,表示永不超時。如果超時,則直接拋出JedisConnectionException
spring.redis.jedis.pool.max-wait=10000

  創建Jedis連接池配置類JedisPoolFactory:

package com.eg.wiener.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class JedisPoolFactory {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;

    /**
     * 初始化Redis連接池
     */     
    @Bean
    public JedisPool generateJedisPoolFactory() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxWaitMillis(maxWaitMillis);
          // 連接耗盡時是否阻塞, false報異常,true阻塞直到超時, 默認true 
        poolConfig.setBlockWhenExhausted(Boolean.TRUE);
        JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout);
         // 若設置了Redis密碼,請調用如下構造函數
//        JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout, password);
        return jedisPool;
    }
}

  若設置了Redis密碼,請調用構造函數 new JedisPool(poolConfig, host, port, timeout, password)。

§案例分析

  創建Redis工具類JedisUtil,由於是測試系統是否成功整合redis,所以在工具類中僅僅添加幾個方法:

package com.eg.wiener.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class JedisUtil {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 存儲字符串鍵值對,永久有效
     * @param key
     * @param value
     * @return
     * @author hw
     * @date 2018年12月14日
     */
    public String set(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.set(key, value);
        } catch (Exception e) {
            return "-1";
        } finally {
            // 業務操作完成,將連接歸還連接池
             jedisPool.returnResource(jedis);
        }
    }

    /**
     * 根據傳入key獲取指定Value
     * @param key
     * @return
     * @author hw
     * @date 2018年12月14日
     */
    public String get(String key) {
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.get(key);
        } catch (Exception e) {
            return "-1";
        } finally {
            jedis.close();
        }
    }

    /**
     * 刪除字符串鍵值對
     * @param key
     * @return
     * @author hw
     * @date 2018年12月14日
     */
    public Long del(String key) {
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.del(key);
        } catch (Exception e) {
            return -1L;
        } finally {
            jedis.close();
        }
    }
    /**
     * 校驗Key值是否存在
     */
    public Boolean exists(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.exists(key);
        } catch (Exception e) {
            return false;
        } finally {
             // 歸還連接
            jedis.close();
        }
    }
}

  這里通過連接池來獲取Jedis實例。由於連接池資源有限,所以,業務操作結束后要及時把Jedis實例還給連接池。在UserController類中創建測試用例,一個負責向redis寫數據,一個負責讀,代碼如下:

/**
 * @author Wiener
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);
 
    @Autowired
    private JedisUtil jedisUtil;
    
    // http://localhost:8087/wiener/user/testRedisSave?id=1090330
    @RequestMapping("/testRedisSave")
    public Object testRedisSave(Long id) {
        jedisUtil.del("userId:"+id);
        jedisUtil.set("userId:"+id, "測試地址是 " + UUID.randomUUID().toString());
        return null;
    }
    // http://localhost:8087/wiener/user/testRedisGet?id=1090330
    @RequestMapping("/testRedisGet")
    public String testRedisGet(Long id) {
        String myStr= jedisUtil.get("userId:"+ id);
        if(!StringUtils.isEmpty(myStr)) {
            return myStr;
        }
        return null;
    }
}

  在瀏覽器請求寫入數據的API后,調用讀取testRedisGet函數,執行結果如下圖所示,說明配置JedisPool成功:

§小結

  關於Spring Boot項目集成Jedis操作Redis連接池就先介紹到這里,如果您覺得本文對您有幫助,請點一下“推薦”按鈕,您的【推薦】將是我最大的寫作動力!歡迎各位轉載,但是未經作者本人同意,轉載文章之后必須在文章頁面明顯位置給出作者和原文連接,否則保留追究法律責任的權利。

§Reference


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM