pom文件添加:
<!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
实现代码如下:
import java.util.HashSet; import java.util.Map; import java.util.Set; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; public class Redis { private JedisCluster jedisCluster; public Redis() { String redisString = "redisCluster=192.168.100.46:30601,192.168.100.46:30602,192.168.100.46:30603,192.168.100.46:30604,192.168.100.46:30605,192.168.100.46:30606"; String[] hostArray = redisString.split(","); Set<HostAndPort> nodes = new HashSet<HostAndPort>(); //配置redis集群 for(String host : hostArray) { String[] detail = host.split(":"); nodes.add( new HostAndPort(detail[0] , Integer.parseInt(detail[1])) ); } jedisCluster = new JedisCluster(nodes); } /** * 获取redis中指定key的值,value类型为String的使用此方法 */ public String get(String key) { return jedisCluster.get(key); } /** * 设置redis中指定key的值,value类型为String的使用此方法 */ public void set(String key,String value) { jedisCluster.set(key,value); } /** * 获取redis中指定key的值,对应的value,value类型为MAP的使用此方法 */ public Map<String,String> getMap(String key) { return jedisCluster.hgetAll(key); } /** * 删除redis中指定key的值项 */ public void del(String key) { jedisCluster.del(key); } public static void main(String args[]) { String value = new Redis().get("CompanyTenantID_10005"); System.out.println(value); } }