首頁 Java java教程 java操作redis 叢集的實例詳解

java操作redis 叢集的實例詳解

May 26, 2017 pm 02:38 PM

關於Redis 叢集搭建可以參考我的另一篇文章 Redis叢集建立與簡單使用

Redis 是什麼,可以做什麼

Redis 是開源(BSD許可),記憶體儲存的資料結構伺服器,可用作資料庫,快取和訊息佇列代理。它支援字串、哈希表、列表、集合、有序集合,位圖,hyperloglogs等資料類型。內建複製、Lua腳本、LRU收回、交易以及不同層級磁碟持久化功能,同時透過Redis Sentinel 提供高可用,透過 Redis Cluster 提供自動分割區。 (摘自 Redis 官網)

作為記憶體資料庫,在現代互聯網 web 系統中,還是主要將 Redis 作為快取使用。大型網路Web 系統對效能要求很高,而在前端和資料層之間增加資料快取已成為不可或缺的手段之一,目前比較流行的兩個技術就是 Redis 和 Memcached,至於兩者有什麼區別,不是本文要說的內容。本文主要講 Java web 如何操作 Redis 及 Redis 叢集。

一般 Java 程式操作Redis

Redis 提供了多種語言的客戶端,在 Java 中最受歡迎的是 Jedis 。存取可查看原始碼及使用方式。目前 Jedis 最新版本是2.9.0。無論是單機還是集群,Jedis 都有很詳細的說明和實例程式碼,這裡只做簡單說明。如果用Maven 做套件管理,需要引用 jedis 套件,本例使用最新的2.9.0版本,如下:

  redis.clients      jedis      2.9.0  
操作 Redis 单机
import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig; /** * Created by fengdezitai on 2016/10/9. */public class JedisClient {     private static final String host= "192.168.31.121";     private static final JedisClient jedisClient = new JedisClient();     private Jedis jedis = null;    /**     * 私有构造函数     */    private JedisClient(){}     public static JedisClient getInstance(){        return jedisClient;    }     private JedisPoolConfig getPoolConfig(){        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();        jedisPoolConfig.setMaxIdle(10);        jedisPoolConfig.setMaxTotal(100);        jedisPoolConfig.setMaxWaitMillis(3000);        return jedisPoolConfig;    }     /**     * 添加     * @param key     * @param value     * @return     * @throws Exception     */    public Boolean add(String key,String value) throws Exception{        JedisPool pool = new JedisPool(getPoolConfig(),host);        Jedis jedis = null;        try {            jedis = pool.getResource();            if(jedis.exists(key)){                throw new Exception(String.format("key (%s) 已存在 ",key));            }            jedis.set(key,value);         }catch (Exception e){            throw e;        }        finally {            if(jedis!=null){                jedis.close();            }        }        pool.destroy();        return true;    }     /**     * 获取值     * @param key     * @return     * @throws Exception     */    public String get(String key) throws Exception{        JedisPool pool = new JedisPool(getPoolConfig(),host);        Jedis jedis = null;        String result = "";        try {            jedis = pool.getResource();            result = jedis.get(key);        }catch (Exception e){            throw e;        }        finally {            if(jedis!=null){                jedis.close();            }        }        pool.destroy();        return result;    }     public static void main(String[] args) {        JedisClient jedisClient = JedisClient.getInstance();        try {            /*Boolean result = jedisClient.add("hello", "redis1");            if(result){                System.out.println("success");            }*/             System.out.println(jedisClient.get("hello"));        }catch (Exception e){            e.printStackTrace();        }    }}
登入後複製

操作redis 叢集

import redis.clients.jedis.*;
import java.util.HashSet;
import java.util.Set;
 
/**
 * Created by fengdezitai on 2016/10/13.
 */
public class JedisClusterClient {
 
    private static int count = 0;
 
    private static final JedisClusterClient redisClusterClient = new JedisClusterClient();
 
    /**
     * 私有构造函数
     */
    private JedisClusterClient() {}
 
    public static JedisClusterClient getInstance() {
        return redisClusterClient;
    }
 
    private JedisPoolConfig getPoolConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(1000);
        config.setMaxIdle(100);
        config.setTestOnBorrow(true);
        return config;
    }
 
    public void SaveRedisCluster() {
        Set jedisClusterNodes = new HashSet();
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7000));
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7001));
        jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7002));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7003));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7004));
        jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7005));
 
        JedisCluster jc = new JedisCluster(jedisClusterNodes,getPoolConfig());
        jc.set("cluster", "this is a redis cluster");
        String result = jc.get("cluster");
        System.out.println(result);
    }
 
    public static void main(String[] args) {
        JedisClusterClient jedisClusterClient = JedisClusterClient.getInstance();
        jedisClusterClient.SaveRedisCluster();
    }
}  
登入後複製

#Spring mvc 操作Redis

在Spring mvc 中操作Redis ,首先當然要搭好Spring mvc 框架了。以下是假設 Spring mvc 環境已經架好的情況下。本例中 Spring 版本為 4.3.2 RELEASE。關於Spring 的maven 引用如下:

4.3.2.RELEASE 
    
          org.springframework      spring-core      ${spring.version}                        commons-logging          commons-logging                   
          org.springframework      spring-web      ${spring.version}     
          org.springframework      spring-oxm      ${spring.version}     
          org.springframework      spring-tx      ${spring.version}     
          org.springframework      spring-jdbc      ${spring.version}     
          org.springframework      spring-webmvc      ${spring.version}                        commons-logging          commons-logging                   
          org.springframework      spring-aop      ${spring.version}     
          org.springframework      spring-context-support      ${spring.version}     
 
          org.springframework      spring-test      ${spring.version}
登入後複製

操作Redis 單機

只用Jedis 自己實現注入(區別於下面的引用spring-data-redis) 

把前面的JedisClient 程式碼拿過來引用即可,只要實作一個存取Redis 的Service ,就可以整合到Spring mvc 。 Service 程式碼如下:

import org.springframework.stereotype.Service;
import util.JedisClient;
 
/**
 * Created by fengdezitai on 2016/10/9.
 */
@Service
public class RedisService {
 
    public String get(String key) throws Exception{
        JedisClient jedisClient = JedisClient.getInstance(); //上面实现的JedisClient
        String result = "";
        try {
            result = jedisClient.get("hello");
        }catch (Exception e){
            throw e;
        }
        return result;
    }
}
登入後複製

Controller 實作如下:

@Controller
@RequestMapping(value = "redisAllInOne")
public class RedisAllInOneController {
 
    @Autowired
    private RedisService redisService;
 
    @RequestMapping(value = "get",method = RequestMethod.GET)
    @ResponseBody
    public Object getByMyService(String key){
        try {
            String result = redisService.get(key);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}  
登入後複製

用 spring-data-redis 套件做整合

上面是自己實作的注入,這裡用spring-data- redis 進行集成,只需簡單配置即可,需要引用maven 包如下,版本為目前最新版1.7.2.RELEASE:

      org.springframework.data      spring-data-redis      1.7.2.RELEASE
登入後複製

使用spring-data-redis ,即省去了自己實現注入的流程,透過它提供的一些配置,即可實現連接池配置、RedisTemplate 配置、JedisConnectionFactory 配置;透過 JedisConnectionFactory 可配置連接池參數、redis 伺服器、連接埠、密碼、逾時時間、data索引等;RedisTemplate 即註入的bean ,可以使用 RedisTemplate 自動注入的實體進行redis 的一系列操作,具體看配置;

redis 服務屬性設定檔:

redis.maxIdle=300redis.maxWait=3000redis.testOnBorrow=trueredis.host=192.168.31.121redis.port=6379redis.password=passwordredis.timeout=3000
spring-data-redis xml 配置文件 redis-context.xml:                                                              -->                                                                                                          -->
登入後複製

之後在spring 設定檔中引用以上檔案:

解釋一下上面的配置:

poolConfig 即配置redis 連接池,之後配置了兩個 JedisConnectionFactory 和RedisTemplate ,一個RedisTemplate 對應一個JedisConnectionFactory ,這樣可以配置根據場景配置不同的Redis 連接,例如超時時間要求不一致、database 0-15 可以儲存不同的資料等。這裡設定了database 1 和 2 ,呼叫 commonRedisTemplate 會存到 database1 ,呼叫 cacheRedisTemplate 會存到 database2。

之後在Service 層即可注入並引用這兩個RedisTemplate ,如下程式碼:

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
 
import javax.annotation.Resource;
import java.io.*;
 
@Repository
public class RedisCache {  
    @Resource(name = "cacheRedisTemplate")
    private RedisTemplate
登入後複製

最後在Controller 中呼叫即可

@Autowired
private RedisCache redisCache;
 
 
@RequestMapping(value = "get", method = RequestMethod.GET)
@ResponseBody
public Object getByMyService(String key) {
    try {
        String result = redisService.get(key);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
@RequestMapping(value = "save", method = RequestMethod.GET)
@ResponseBody
public Object save() {
    Token token = new Token();
    token.setAccess_token("token");
    token.setExpires_in(1000);
    try {
        redisCache.put("token", token);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "ok";
}  
登入後複製

操作Redis 集群

只用Jedis 自己實作注入(有別於下面的引用spring-data-redis)

把前面的 JedisClusterClient 程式碼拿過來引用即可,只要實作一個存取Redis 的Service ,就可以整合到Spring mvc 。 Service 程式碼如下:

import org.springframework.stereotype.Service;
import util.JedisClusterClient;
 
/**
 * Created by fengdezitai on 2016/10/13.
 */
@Service
public class RedisClusterService {
 
    public void save() throws Exception{
        //调用 JedisClusterClient 中的方法
        JedisClusterClient jedisClusterClient = JedisClusterClient.getInstance();
        try {
            jedisClusterClient.SaveRedisCluster();
        }catch (Exception e){
            throw e;
        }
    }
}
登入後複製

最後在Controller 中呼叫實作的Service 即可

@Controller
@RequestMapping(value = "redisCluster")
public class RedisClusterController {
 
    @Autowired
    private RedisClusterService redisClusterService;
 
    @RequestMapping(value = "save",method = RequestMethod.GET)
    @ResponseBody
    public Object save(){
        try{
            redisClusterService.save();
        }catch (Exception e){
            e.printStackTrace();
            return String.format("error: %s",e.getMessage());
        }
        return "ok";
    }
}  
登入後複製

注意事項:

版本問題,如果用 spring-data-redis 做整合操作Reids 集群,只有 spring-data-redis 目前最新版本1.7才包含對集群的操作,而最新的 spring-data-redis 中的某些功能對Spring mvc 的版本也有些限制,所以盡量選擇高版本的 Spring mvc對應。

如果儲存的value值是一個實體對象,那麼一定要實作 Serializable 介面

【相關推薦】

1. 詳解Spring框架註解的用法代碼實例

2. Java事務管理學習之Spring和Hibernate的程式碼詳解

3. 分享利用Spring Boot開發Restful程式的實例教程

4. 詳解spring mvc支援的七種返回方式

5. 關於Spring基於Aspect 的增強實作實例詳解

6. PHPRPC for Java Spring的例子

#8. 詳解spring中使用Elasticsearch的實例教學

以上是java操作redis 叢集的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PHP與Python:了解差異 PHP與Python:了解差異 Apr 11, 2025 am 12:15 AM

PHP和Python各有優勢,選擇應基於項目需求。 1.PHP適合web開發,語法簡單,執行效率高。 2.Python適用於數據科學和機器學習,語法簡潔,庫豐富。

redis集群模式怎麼搭建 redis集群模式怎麼搭建 Apr 10, 2025 pm 10:15 PM

Redis集群模式通過分片將Redis實例部署到多個服務器,提高可擴展性和可用性。搭建步驟如下:創建奇數個Redis實例,端口不同;創建3個sentinel實例,監控Redis實例並進行故障轉移;配置sentinel配置文件,添加監控Redis實例信息和故障轉移設置;配置Redis實例配置文件,啟用集群模式並指定集群信息文件路徑;創建nodes.conf文件,包含各Redis實例的信息;啟動集群,執行create命令創建集群並指定副本數量;登錄集群執行CLUSTER INFO命令驗證集群狀態;使

redis指令怎麼用 redis指令怎麼用 Apr 10, 2025 pm 08:45 PM

使用 Redis 指令需要以下步驟:打開 Redis 客戶端。輸入指令(動詞 鍵 值)。提供所需參數(因指令而異)。按 Enter 執行指令。 Redis 返迴響應,指示操作結果(通常為 OK 或 -ERR)。

redis怎麼啟動服務器 redis怎麼啟動服務器 Apr 10, 2025 pm 08:12 PM

啟動 Redis 服務器的步驟包括:根據操作系統安裝 Redis。通過 redis-server(Linux/macOS)或 redis-server.exe(Windows)啟動 Redis 服務。使用 redis-cli ping(Linux/macOS)或 redis-cli.exe ping(Windows)命令檢查服務狀態。使用 Redis 客戶端,如 redis-cli、Python 或 Node.js,訪問服務器。

redis怎麼讀取隊列 redis怎麼讀取隊列 Apr 10, 2025 pm 10:12 PM

要從 Redis 讀取隊列,需要獲取隊列名稱、使用 LPOP 命令讀取元素,並處理空隊列。具體步驟如下:獲取隊列名稱:以 "queue:" 前綴命名,如 "queue:my-queue"。使用 LPOP 命令:從隊列頭部彈出元素並返回其值,如 LPOP queue:my-queue。處理空隊列:如果隊列為空,LPOP 返回 nil,可先檢查隊列是否存在再讀取元素。

redis底層怎麼實現 redis底層怎麼實現 Apr 10, 2025 pm 07:21 PM

Redis 使用哈希表存儲數據,支持字符串、列表、哈希表、集合和有序集合等數據結構。 Redis 通過快照 (RDB) 和追加只寫 (AOF) 機制持久化數據。 Redis 使用主從復制來提高數據可用性。 Redis 使用單線程事件循環處理連接和命令,保證數據原子性和一致性。 Redis 為鍵設置過期時間,並使用 lazy 刪除機制刪除過期鍵。

redis怎麼讀源碼 redis怎麼讀源碼 Apr 10, 2025 pm 08:27 PM

理解 Redis 源碼的最佳方法是逐步進行:熟悉 Redis 基礎知識。選擇一個特定的模塊或功能作為起點。從模塊或功能的入口點開始,逐行查看代碼。通過函數調用鏈查看代碼。熟悉 Redis 使用的底層數據結構。識別 Redis 使用的算法。

redis怎麼使用鎖 redis怎麼使用鎖 Apr 10, 2025 pm 08:39 PM

使用Redis進行鎖操作需要通過SETNX命令獲取鎖,然後使用EXPIRE命令設置過期時間。具體步驟為:(1) 使用SETNX命令嘗試設置一個鍵值對;(2) 使用EXPIRE命令為鎖設置過期時間;(3) 當不再需要鎖時,使用DEL命令刪除該鎖。

See all articles