18 Java与redis集群的通信

2023-12-13 21:56:37
1、引入依赖
<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.6.3</version>
        </dependency>
2、配置
# Redis集群服务器地址
redis.nodes=aliyun:6900,aliyun:6901,aliyun:6902,aliyun:6930,aliyun:6931,aliyun:6932
#在集群中执行命令时要遵循的最大重定向数目
redis.cluster.max-redirects=5
# Redis服务器连接密码(默认为空)
redis.password=null
redis.timeout=30000
# 连接池最大连接数(使用负值表示没有限制)
redis.maxTotal=30
# 连接池中的最大空闲连接
redis.maxIdle=10
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000
redis.minEvictableIdleTimeMillis=1800000
redis.softMinEvictableIdleTimeMillis=10000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
redis.maxWaitMillis=1500
redis.testOnBorrow=true
redis.testWhileIdle=true
redis.blockWhenExhausted=false
redis.JmxEnabled=true
3、获取api对象
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

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

@Configuration
@PropertySource("classpath:application.properties")
public class RedisClusterConfig {
    @Value("${redis.nodes}")
    private String hosts;

    @Value("${redis.cluster.max-redirects}")
    private int maxRedirects;

    @Value("${redis.timeout}")
    private int timeout;

    @Value("${redis.maxIdle}")
    private int maxIdle;

    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;

    @Value("${redis.blockWhenExhausted}")
    private Boolean blockWhenExhausted;

    @Value("${redis.JmxEnabled}")
    private Boolean JmxEnabled;

    @Bean
    public JedisPoolConfig  jedisPoolConfigFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        // 连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(JmxEnabled);

        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);
        return jedisPoolConfig;
    }

    @Bean
    public JedisCluster getJedisCluster(JedisPoolConfig jedisPoolConfig) {
        Set<HostAndPort> nodes = new HashSet<>();
        String[] hostsArray = hosts.split(",");
        for (String ipPort : hostsArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        return new JedisCluster(nodes,timeout,1000,1,jedisPoolConfig);
    }

}
4、操作String类型示例
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisSentinelPool;

/**
 * 操作字符串类型
 */
@Component
public class RedisString {

    public final static String RS_STR_NS = "rs:";

    @Autowired
    private JedisCluster jedisCluster;

    /**
     * 向Redis中存值,永久有效
     */
    public String set(String key, String value) {
        try {
            return jedisCluster.set(RS_STR_NS +key, value);
        } catch (Exception e) {
            throw new RuntimeException("向Redis中存值失败!");
        } finally {
        }
    }

    /**
     * 根据传入Key获取指定Value
     */
    public String get(String key) {
        try {
            return jedisCluster.get(RS_STR_NS +key);
        } catch (Exception e) {
            throw new RuntimeException("获取Redis值失败!");
        } finally {
        }
    }

}
5、测试
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class TestRedisString {

    @Autowired
    private RedisString redisString;

    @Test
    void testSet(){
        System.out.println(redisString.set("test","Hello Java"));
    }

    @Test
    void testGet(){
        System.out.println(redisString.get("test"));
    }
}

文章来源:https://blog.csdn.net/weixin_39563769/article/details/134902718
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。