1. 程式人生 > >springboot之整合jedis的使用

springboot之整合jedis的使用

在pom.xml匯入jedis包 

<!--redis客戶端-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

單機版

在resources下建立redis.properties檔案,裡面配置自己的redis的ip和埠號 ,如果自己想設定其它的屬性的話也可以自己加幾個

然後往ioc容器中加入JedisPool物件,因為使用了springboot了,就最好不用使用spring配置檔案了,所以就使用java類註解方式建立這個物件

package com.buba.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@SpringBootConfiguration
@PropertySource(value = {"classpath:redis/redis.properties"})
public class RedisConfiguration {
    @Value("${redis.node.maxTotal}")
    private Integer maxTotal;
    @Value("${redis.node.host}")
    private String host;
    @Value("${redis.node.port}")
    private Integer port;

    public JedisPoolConfig jedisPoolConfig(){    //這個是修改redis效能的時候需要的物件
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        return jedisPoolConfig;
    }

    @Bean  //這個註解注入工廠的名稱是方法名
    public JedisPool jedisPool(){
        JedisPoolConfig jedisPoolConfig = jedisPoolConfig();
        return new JedisPool(jedisPoolConfig,host,port);
    }
}

然後進行測試 

叢集版

同樣先導包,相同的包

然後寫配置檔案

然後寫配置類,沒啥邏輯就是把字串按照那格式分割開

 

package com.buba.configuration;

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

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

@SpringBootConfiguration
@PropertySource(value = {"classpath:redis/redisCluster.properties"})
public class RedisClusterConfiguration {

    @Value("${redis.cluster.nodes}")
    private String nodes;

    @Bean
    public JedisCluster jedisCluster(){
        Set<HostAndPort> set = new HashSet<>();
        HostAndPort hp = null;
        String[] nodeStr = nodes.split(",");
        if(nodeStr!=null&&nodeStr.length>0){
            for(int i=0;i<nodeStr.length;i++){
                String[] hostPort = nodeStr[i].split(":");
                if(hostPort!=null&&hostPort.length>0){
                    hp = new HostAndPort(hostPort[0],Integer.valueOf(hostPort[1]));
                    set.add(hp);
                }
            }
        }
        JedisCluster jedisCluster = new JedisCluster(set);
        return jedisCluster;
    }

}

然後進行測試,測試前先開啟redis叢集,然後關閉防火牆 

還有一種方式就是還是之前的ssm建立spring配置檔案,然後寫bean物件注入 

這個是建立spring配置檔案方式https://blog.csdn.net/kxj19980524/article/details/84890268

這個是springboot讀取spring配置檔案方式https://blog.csdn.net/kxj19980524/article/details/85156778