SpringBoot 2.0 如何使用Redis-Cluster

阿爾法貓發表於2018-08-05

SpringBoot2.0對Redis-Cluster的使用提供了支援,這也是我比較喜歡使用SpringBoot的原因之一,減少配置,加快開發速度。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <articleId>spring-boot-starter-data-redis</article>
</dependency>複製程式碼

一、yml配置

spring:
  redis:
    jedis:
      pool:
        max-wait:5000
        max-Idle:50
        min-Idle:5
    cluster:
      nodes:127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003,127.0.0.1:7004,127.0.0.1:7005,127.0.0.1:7006
    timeout:500複製程式碼

二、使用推薦的RedisTemplate使用Redis-Cluster

RedisClusterConfiguration.java

@Configuration
public class RedisClusterConfiguration{

       @Bean
       public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory redisConnectionfactory){
              RedisTemplate<String,String> redisTemplate=new RedisTemplate<>();
              redisTemplate.setConnectionFactory(redisConnectionFactory);
              redisTemplate.setKeySerializer(new StringRedisSerializer());
              redisTemplate.setValueSerializer(new StringRedisSerializer());
              redisTemplate.afterPropertiesSet();
              return redisTemplate;
       }
}複製程式碼

單元測試

RedisClusterTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisClusterTest{
    
        @Autowire
       private RedisTemplate<String,String> redisTemplate;

 
       @Test
       public void getValue(){
            ValueOperations<String,String> operations=redisTemplate.opsForValue();
            System.out.println(operations.get("key1"));
      }
}複製程式碼

在前一篇當中我們在Redis-Cluster中存入了key1-value1這樣的鍵值對,位置在Slot[2292]

輸出:"value1"

這是springboot2.0的新的功能,如果使用springboot1.x的話,得使用jedisCluster這樣的類,當然也可以在springboot2中使用jedisCluster,當然也可以在springMvc中使用,沒有版本上的限制。

三、JedisCluster使用Redis-Cluster

<dependency>
    <groupId>redis.clients</groupId>
    <articleId>jedis</articleId>
</dependency>複製程式碼

application.yml配置

springmvc下支援.properties檔案,請自改

  #redis叢集配置  
  redis:  
    # Redis伺服器連線密碼(預設為空)   
    password: *****  
    jedis:  
      pool:  
       # 連線池最大連線數(使用負值表示沒有限制)  
        max-active: 5000  
       # 連線池最大阻塞等待時間(使用負值表示沒有限制)     
        max-wait: -1  
       # 連線池中的最大空閒連線  
        max-idle: 30  
       # 連線池中的最小空閒連線   
        min-idle: 5  
    # 連線超時時間(毫秒)  
    timeout: 50000  
    commandTimeout: 50000  
    #叢集  
    cluster:  
      nodes: 192.168.0.159:7001,192.168.0.159:7002,192.168.0.159:7003,192.168.0.159:7004,192.168.0.159:7005,192.168.0.159:7006  
複製程式碼

RedisConfig.class-java Config配置

import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

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

@Configuration
@ConditionalOnClass({JedisCluster.class})
public class RedisConfig{
   
    @Value("${spring.redis.cluster.nodes}")  
    private String clusterNodes;  
    @Value("${spring.redis.timeout}")  
    private int timeout;  
    @Value("${spring.redis.jedis.pool.max-idle}")  
    private int maxIdle;  
    @Value("${spring.redis.jedis.pool.max-wait}")  
    private long maxWaitMillis;  
    @Value("${spring.redis.commandTimeout}")  
    private int commandTimeout;
    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public JedisCluster getJedisCluster(){
          String[] cNodes=ClusterNodes.split(",");
          Set<HostAndPort> node=new HashSet<HostAndPort>();
          //分割出叢集點
          for(String node:cNodes){
             String[] hp=node.split(":");
             nodes.add(new HostAndPort(hp[0],Integer.parseInt(hp[1])));
          }
          JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
          jedisPoolConfig.setMaxIdle(maxIdle);
	  jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
          JedisCluster jedisCluster=new JedisCluster(nodes,commandTimeout,timeout,maxIdle,password,jedisPoolConfig);
          return jedisCluster;
   }
}複製程式碼

編寫使用工具類

JedisUtils.java

mport org.springframework.beans.factory.annotation.Autowired;import redis.clients.jedis.JedisCluster;public class JedisClientCluster implements JedisClient {	@Autowired	private JedisCluster jedisCluster;

        @Override	public String set(String key, String value) {		return jedisCluster.set(key, value);	} 	@Override	public String get(String key) {		return jedisCluster.get(key);	} 	@Override	public Boolean exists(String key) {		return jedisCluster.exists(key);	} 	@Override	public Long expire(String key, int seconds) {		return jedisCluster.expire(key, seconds);	} 	@Override	public Long ttl(String key) {		return jedisCluster.ttl(key);	} 	@Override	public Long incr(String key) {		return jedisCluster.incr(key);	} 	@Override	public Long hset(String key, String field, String value) {		return jedisCluster.hset(key, field, value);	} 	@Override	public String hget(String key, String field) {		return jedisCluster.hget(key, field);	} 	@Override	public Long hdel(String key, String... field) {		return jedisCluster.hdel(key, field);	} }
       複製程式碼

springmvc版-applicationContext-redis.xml配置

<bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">		<constructor-arg>			<set>				<bean class="redis.clients.jedis.HostAndPort">					<constructor-arg name="host" value="192.168.25.153"></constructor-arg>					<constructor-arg name="port" value="7001"></constructor-arg>				</bean>				<bean class="redis.clients.jedis.HostAndPort">					<constructor-arg name="host" value="192.168.25.153"></constructor-arg>					<constructor-arg name="port" value="7002"></constructor-arg>				</bean>				<bean class="redis.clients.jedis.HostAndPort">					<constructor-arg name="host" value="192.168.25.153"></constructor-arg>					<constructor-arg name="port" value="7003"></constructor-arg>				</bean>				<bean class="redis.clients.jedis.HostAndPort">					<constructor-arg name="host" value="192.168.25.153"></constructor-arg>					<constructor-arg name="port" value="7004"></constructor-arg>				</bean>				<bean class="redis.clients.jedis.HostAndPort">					<constructor-arg name="host" value="192.168.25.153"></constructor-arg>					<constructor-arg name="port" value="7005"></constructor-arg>				</bean>				<bean class="redis.clients.jedis.HostAndPort">					<constructor-arg name="host" value="192.168.25.153"></constructor-arg>					<constructor-arg name="port" value="7006"></constructor-arg>				</bean>			</set>		</constructor-arg>	</bean>複製程式碼

測試

如果是springboot的話與上一致

Spring mvc測試

        @Test	public void testJedisClient() throws Exception {		//初始化Spring容器		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml");		//從容器中獲得JedisClient物件		JedisClient jedisClient = applicationContext.getBean(JedisClient.class);		jedisClient.set("first", "100");		String result = jedisClient.get("first");
        }複製程式碼

注:這只是簡單的使用redis叢集,如果專案的處理邏輯並不複雜只是考慮資料量和併發度,可以使用這樣的架構。但使用實戰的話還是有所欠缺,還需要好好學習技術和架構。

勉勵~


相關文章