在单机Redis环境:Jedis
Jedis jedis = new Jedis("url", 8001);
在多台Redis环境(没有集群):ShardedJedis+ShardedJedisPool
@Configuration
@ConditionalOnExpression("${gcloud.redis.jedisClient.enable:false} == true")
public class JedisConfig {
@Value("${spring.redis.host:}")
private String host;
@Value("${spring.redis.port:}")
private Integer port;
@Value("${spring.redis.timeout:}")
private Integer timeout;
@Value("${spring.redis.pool.max-idle:}")
private Integer maxIdle;
@Value("${spring.redis.pool.max-wait:}")
private Long maxWaitMillis;
@Value("${spring.redis.pool.max-active:}")
private Integer maxActive;
@Value("${spring.redis.password:}")
private String password;
@Bean
public ShardedJedisPool shardedJedisPool() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
if(maxActive != null){
jedisPoolConfig.setMaxTotal(maxActive);
}
if(maxIdle != null){
jedisPoolConfig.setMaxIdle(maxIdle);
}
if(maxWaitMillis != null){
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
}
List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>();
jedisShardInfoList.add(new JedisShardInfo(host, port));
return new ShardedJedisPool(jedisPoolConfig, jedisShardInfoList);
}
在Redis集群环境:JedisCluster
- Set<HostAndPort> nodes = new HashSet<>();
- nodes.add(new HostAndPort("192.168.25.153", 7001));
- nodes.add(new HostAndPort("192.168.25.153", 7002));
- nodes.add(new HostAndPort("192.168.25.153", 7003));
- nodes.add(new HostAndPort("192.168.25.153", 7004));
- nodes.add(new HostAndPort("192.168.25.153", 7005));
- nodes.add(new HostAndPort("192.168.25.153", 7006));
- JedisCluster jedisCluster = new JedisCluster(nodes);
- // 第二步:直接使用JedisCluster对象操作redis。在系统中单例存在。
- jedisCluster.set("hello", "100");
- String result = jedisCluster.get("hello");
- // 第三步:打印结果
- System.out.println(result);
- // 第四步:系统关闭前,关闭JedisCluster对象。
- jedisCluster.close();