详细参考这篇文章(windows)java
https://blog.csdn.net/qiuyufeng/article/details/70474001node
1、使用JAVA代码操做redis集群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(); } }
2、使用JAVA代码操做lua脚本windows
一、编写lua脚本lua
redis.call(\"SET\",KEYS[1],ARGV[1]);\n" + "redis.call(\"SET\",KEYS[2],ARGV[2]);
二、java代码spa
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]);\n" + "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值;.net
能够参考这篇文章https://blog.csdn.net/jing956899449/article/details/53338282code