搜尋
首頁Javajava教程java操作redis 叢集的實例詳解

關於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
如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?Mar 17, 2025 pm 05:46 PM

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?Mar 17, 2025 pm 05:45 PM

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?Mar 17, 2025 pm 05:44 PM

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?Mar 17, 2025 pm 05:43 PM

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Mar 17, 2025 pm 05:35 PM

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

See all articles

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

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具