1. 程式人生 > >springboot 整合 redis叢集(window版本)

springboot 整合 redis叢集(window版本)

說實話,很麻煩 

然後,複製到6個redis檔案,修改每個檔案裡的redis.windows.conf 檔案 


port 6378
cluster-enabled yes
cluster-config-file nodes-6378.conf
cluster-node-timeout 5000
appendonly yes

這裡的 port 和 cluster-config-file 6個都要修改成 遞增 6378 6379 。。。6384

之後每個資料夾裡面都新增一個指令碼


用來啟動對應資料夾的redis(不同埠),然後分別手動執行這個指令碼,開啟到六個視窗


接著,下載ruby 附上鍊接 http://railsinstaller.org/en

 安裝時候記得選上給你設定環境變數,然後在命令提示符視窗(dos視窗)(window鍵+R 輸入 cmd 回車)設定以下操作


再去redis官網下載 linux版本的redis,因為需要redis-trib.rb這個檔案來進行叢集管理,而window版本下載後沒有這個檔案。


把這個檔案解壓到redis前一層目錄下(其實隨意,好管理吧)

在命令提示符視窗(dos視窗),切換到redis-trib.rb檔案的目錄下,執行下面命令

ruby redis-trib.rb create --replicas 1 127.0.0.1:6379 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 127.0.0.1:6383 127.0.0.1:6384

這裡需要六個節點,也就是之前複製和開啟六個redis的原因

我在之前設定三個節點叢集發現的問題,這裡3個是master,應該主要是 --replicas 1 這個引數

成功的圖片


這裡之後就可以做java部分的操作了,匯入jedis依賴包

	<dependency>  
            <groupId>redis.clients</groupId>  
            <artifactId>jedis</artifactId>  
            <version>2.8.2</version>  
        </dependency> 

在 springboot 讀取的application.properties檔案,寫下配置

#redis叢集配置  
cl.redis.pool.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384
cl.redis.pool.timeout=3000  
cl.redis.pool.maxAttempts=5 

然後建立redis的屬性類 自動裝配類 樣版類

redis屬性類:

package com.java.Olym.redisCluster;

import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**  
 * redis叢集配置檔案   
 */  
@Component  
@ConfigurationProperties(prefix = "cl.redis.pool")  
//@PropertySource("classpath:application.properties")  
public class RedisProperties {  
      
    /** redis叢集節點 */  
    private String nodes;  
    /** 連線超時時間 */  
    private int timeout;  
    /** 重連次數 */  
    private int maxAttempts;  
    public String getNodes() {  
        return nodes;  
    }  
    public void setNodes(String nodes) {  
        this.nodes = nodes;  
    }  
    public int getTimeout() {  
        return timeout;  
    }  
    public void setTimeout(int timeout) {  
        this.timeout = timeout;  
    }  
    public int getMaxAttempts() {  
        return maxAttempts;  
    }  
    public void setMaxAttempts(int maxAttempts) {  
        this.maxAttempts = maxAttempts;  
    }  
      
}  

redis自動裝配類:

package com.java.Olym.redisCluster;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

/**  
 * 生成JedisCluster物件  
 */  
@Configuration  
public class JedisClusterConfig {  
    @Autowired  
    private RedisProperties redisProperties;   

    @Bean(name="jedisCluster") 
    public JedisCluster getJedisCluster() {  
        String[] serverArray = redisProperties.getNodes().split(",");  
        Set<HostAndPort> nodes = new HashSet<>();  
        for (String ipPort : serverArray) {  
            String[] ipPortPair = ipPort.split(":");  
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));  
        }  
        return new JedisCluster(nodes, redisProperties.getTimeout(),redisProperties.getMaxAttempts());  
    }  
  
} 

redis模板類:

package com.java.Olym.redisCluster;

import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Component;  
  
import redis.clients.jedis.JedisCluster;  
   
@Component  
public class ClRedisTemplate {  
    private static final Logger LOGGER    = LoggerFactory.getLogger(ClRedisTemplate.class);  
  
    @Autowired  
    private JedisCluster        jedisCluster;  
  
    @Autowired  
    private RedisProperties     redisProperties;  
  
    private static final String KEY_SPLIT = ":"; //用於隔開快取字首與快取鍵值   
  
    /**  
     * 設定快取   
     * @param prefix 快取字首(用於區分快取,防止快取鍵值重複)  
     * @param key    快取key  
     * @param value  快取value  
     */  
    public void set(String prefix, String key, String value) {  
        jedisCluster.set(prefix + KEY_SPLIT + key, value);  
        LOGGER.debug("RedisUtil:set cache key={},value={}", prefix + KEY_SPLIT + key, value);  
    }  
  
    /**  
     * 設定快取,並且自己指定過期時間  
     * @param prefix  
     * @param key  
     * @param value  
     * @param expireTime 過期時間  
     */  
    public void setWithExpireTime(String prefix, String key, String value, int expireTime) {  
        jedisCluster.setex(prefix + KEY_SPLIT + key, expireTime, value);  
        LOGGER.debug("RedisUtil:setWithExpireTime cache key={},value={},expireTime={}", prefix + KEY_SPLIT + key, value,  
            expireTime);  
    }  
  
    /**  
     * 設定快取,並且由配置檔案指定過期時間  
     * @param prefix  
     * @param key  
     * @param value  
     */  
    public void setWithExpireTime(String prefix, String key, String value) {  
        int EXPIRE_SECONDS = redisProperties.getTimeout();  
        jedisCluster.setex(prefix + KEY_SPLIT + key, EXPIRE_SECONDS, value);  
        LOGGER.debug("RedisUtil:setWithExpireTime cache key={},value={},expireTime={}", prefix + KEY_SPLIT + key, value,  
            EXPIRE_SECONDS);  
    }  
  
    /**  
     * 獲取指定key的快取  
     * @param prefix  
     * @param key  
     */  
    public String get(String prefix, String key) {  
        String value = jedisCluster.get(prefix + KEY_SPLIT + key);  
        LOGGER.debug("RedisUtil:get cache key={},value={}", prefix + KEY_SPLIT + key, value);  
        return value;  
    }  
  
    /**  
     * 刪除指定key的快取  
     * @param prefix  
     * @param key  
     */  
    public void deleteWithPrefix(String prefix, String key) {  
        jedisCluster.del(prefix + KEY_SPLIT + key);  
        LOGGER.debug("RedisUtil:delete cache key={}", prefix + KEY_SPLIT + key);  
    }  
      
    public void delete(String key) {  
        jedisCluster.del(key);  
        LOGGER.debug("RedisUtil:delete cache key={}", key);  
    }  
  
}  

最後是測試的 RedisController:

package com.java.Olym.explore.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.java.Olym.redis.RedisClient;
import com.java.Olym.redisCluster.ClRedisTemplate;

@RequestMapping("redis")
@RestController
public class RedisController {

	@Autowired  
	private ClRedisTemplate clRedisTemplate; 
	
	@RequestMapping("setter")
	public String setter(String key,String value){
		clRedisTemplate.set("rc", key, value);
		return "yes";
	}
	@RequestMapping("getter")
	public String getter(String key){
		return clRedisTemplate.get("rc", key);
	}
}
還有主頁jsp測試程式碼
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<%@ include file="./res.jsp"%>
<html>
<head>
<script>
function set(){
	var key = $('input[name="key1"]').val();
	var value = $('input[name="value1"]').val();
	$.getJSON('<%=ctx%>/redis/setter',{"key":key,"value":value},function(result1){
		if(result1!=null){
			alert(result1)
		}
	});
}

function get(){
	var key = $('input[name="key1"]').val();
	$.getJSON("<%=ctx%>/redis/getter",{"key":key},function(result1){
		if(result1!=null){
			$('input[name="value1"]').val(result1);
		}
	});
}
</script>
</head>
<body>
	<h1>Hello World!</h1>
	<div id="redisCluster">
		<span>輸入key<input type="text" name="key1" ></span><p>
		<span>輸入value<input type="text" name="value1" ></span><p>
		<input type="button" value="提交" id="set" onclick="set();"><p>
		<input type="button" value="拿取" id="get" onclick="get();"><p>
	</div>
</body>
</html>

然後就可以測試了


點選提交和拿取,後臺console打印出日誌


成功!!!