springboot整合redis單機及集群


一、單機配置

properties配置

#單機redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=redis

啟動類加

@EnableCaching

具體的方法上加

@Cacheable(value="userList")

這樣的話,redis 中key值即為userList,value 為方法的返回值。pojo可能會需要序列化。

二、集群配置

properties配置

#集群redis節點以及端口
#spring.redis.cluster.nodes=192.168.1.127:7550,192.168.1.127:7551,192.168.1.127:7552,192.168.1.127:7553

RedisClusterConfig

package com.dc.sb.web.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

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

/**
 * redis 集群配置類
 * 需要時直接   @Autowired JedisCluster
 * @author DUCHONG
 * @since 2018-12-17 17:28
 **/
@Configuration
public class RedisClusterConfig {

    @Value("spring.redis.cluster.nodes")
    private String redisNodes;

    @Bean
    public JedisCluster getJedisCluster(){

        Set<HostAndPort> nodes=new HashSet<HostAndPort>() ;

        String [] redisnodes=redisNodes.split(",");
        for (String redisnode : redisnodes) {

            String [] arr=redisnode.split(":");
            HostAndPort hostAndPort=new HostAndPort(arr[0],Integer.parseInt(arr[1]));
            nodes.add(hostAndPort);
        }

        return new JedisCluster(nodes);
    }
}

使用時直接

@Autowired 
private JedisCluster jedisCluster

 


免責聲明!

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



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