详细参考这篇文章(windows)
https://blog.csdn.net/qiuyufeng/article/details/70474001
一、使用JAVA代码操作redis集群
public static void main(String[] args) throws Exception { JedisPoolConfig poolConfig = new JedisPoolConfig(); // 最大连接数 poolConfig.setMaxTotal(1); // 最大空闲数 poolConfig.setMaxIdle(1); // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常: // Could not get a resource from the pool poolConfig.setMaxWaitMillis(1000); Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>(); nodes.add(new HostAndPort("127.0.0.1", 6379)); nodes.add(new HostAndPort("127.0.0.1", 6380)); nodes.add(new HostAndPort("127.0.0.1", 6381)); nodes.add(new HostAndPort("127.0.0.1", 6382)); nodes.add(new HostAndPort("127.0.0.1", 6383)); nodes.add(new HostAndPort("127.0.0.1", 6384)); JedisCluster cluster = new JedisCluster(nodes, poolConfig); String name = cluster.get("name"); System.out.println(name); cluster.set("age", "18"); System.out.println(cluster.get("age")); try { cluster.close(); } catch (IOException e) { e.printStackTrace(); } }
二、使用JAVA代码操作lua脚本
1、编写lua脚本
redis.call("SET",KEYS[1],ARGV[1]); " + "redis.call("SET",KEYS[2],ARGV[2]);
2、java代码
public static void main(String[] args) throws Exception { JedisPoolConfig poolConfig = new JedisPoolConfig(); // 最大连接数 poolConfig.setMaxTotal(1); // 最大空闲数 poolConfig.setMaxIdle(1); // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常: // Could not get a resource from the pool poolConfig.setMaxWaitMillis(1000); Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>(); nodes.add(new HostAndPort("127.0.0.1", 6379)); nodes.add(new HostAndPort("127.0.0.1", 6380)); nodes.add(new HostAndPort("127.0.0.1", 6381)); nodes.add(new HostAndPort("127.0.0.1", 6382)); nodes.add(new HostAndPort("127.0.0.1", 6383)); nodes.add(new HostAndPort("127.0.0.1", 6384)); JedisCluster cluster = new JedisCluster(nodes, poolConfig); String lua = "redis.call("SET",KEYS[1],ARGV[1]); " + "redis.call("SET",KEYS[2],ARGV[2]);"; String[] p = {"{a}a1","{a}a2","a","b"}; Object eval = cluster.eval(lua, 2, p); try { cluster.close(); } catch (IOException e) { e.printStackTrace(); }
需要注意的时,redis集群执行lua操作的时候,要求key值必须要在同一个solt上面,为了达到这个目的,可以在key值中增加“{xx}”内容,这样redis在计算hash槽的时候会按{}内的内容计算hash值;
可以参考这篇文章https://blog.csdn.net/jing956899449/article/details/53338282