RedisTemplate执行lua脚本,集群模式下报错解决

 

redis集群配置:

在使用spring的RedisTemplate执行lua脚本时,报错EvalSha is not supported in cluster environment,不支持cluster。

代码:

    @Test
    public void test4() throws Exception {
        DefaultRedisScript script = new DefaultRedisScript();
        script.setScriptSource(new StaticScriptSource("redis.call('SET', KEYS[1], ARGV[1]); return ARGV[1]"));
        script.setResultType(String.class);
        Object result = redisTemplate.execute(script, Arrays.asList("test_key1"), Arrays.asList("hello,key1"));
        System.out.println(result);
    }

报错信息:

org.springframework.dao.InvalidDataAccessApiUsageException: EvalSha is not supported in cluster environment.

	at org.springframework.data.redis.connection.jedis.JedisClusterConnection.evalSha(JedisClusterConnection.java:3561)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.data.redis.core.CloseSuppressingInvocationHandler.invoke(CloseSuppressingInvocationHandler.java:57)
	at com.sun.proxy.$Proxy136.evalSha(Unknown Source)
	at org.springframework.data.redis.core.script.DefaultScriptExecutor.eval(DefaultScriptExecutor.java:81)
	at org.springframework.data.redis.core.script.DefaultScriptExecutor$1.doInRedis(DefaultScriptExecutor.java:71)
	at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:207)
	at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169)
	at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:157)
	at org.springframework.data.redis.core.script.DefaultScriptExecutor.execute(DefaultScriptExecutor.java:60)
	at org.springframework.data.redis.core.script.DefaultScriptExecutor.execute(DefaultScriptExecutor.java:54)
	at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:300)
	at com.wwwarehouse.xdw.contractcenter.zzz.RedisTest.test4(RedisTest.java:70)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

 

但是redis是支持lua脚本的,只要拿到原redis的connection对象,通过connection去执行即可:

    @Test
    public void test5() throws Exception {
        List<String> keys = new ArrayList<String>();
        keys.add("test_key1");
        List<String> args = new ArrayList<String>();
        args.add("hello,key1");
        String LUA = "redis.call('SET', KEYS[1], ARGV[1]); return ARGV[1]";
        //spring自带的执行脚本方法中,集群模式直接抛出不支持执行脚本异常,此处拿到原redis的connection执行脚本
        String result = (String)redisTemplate.execute(new RedisCallback<String>() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                Object nativeConnection = connection.getNativeConnection();
                // 集群模式和单点模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
                // 集群
                if (nativeConnection instanceof JedisCluster) {
                    return (String) ((JedisCluster) nativeConnection).eval(LUA, keys, args);
                }

                // 单点
                else if (nativeConnection instanceof Jedis) {
                    return (String) ((Jedis) nativeConnection).eval(LUA, keys, args);
                }
                return null;
            }
        });
        System.out.println(result);
    }

输出: hello,key1

 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
### 回答1: redistemplate可以执行lua脚本,可以通过以下步骤实现: 1. 创建一个RedisTemplate对象。 2. 通过RedisTemplate对象获取一个RedisConnection对象。 3. 通过RedisConnection对象执行lua脚本,可以使用RedisConnection的eval()方法。 4. eval()方法的参数包括lua脚本脚本中需要的参数。 5. 执行完毕后,可以通过eval()方法的返回值获取脚本执行结果。 例如: ``` RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); RedisConnection connection = redisTemplate.getConnectionFactory().getConnection(); String script = "return redis.call('get', KEYS[1])"; String result = connection.eval(script.getBytes(), ReturnType.VALUE, 1, "key".getBytes()); ``` 以上代码执行了一个简单的lua脚本,获取了Redis中key为"key"的值。 ### 回答2: redis是一个内存缓存数据库,可用于提高Web应用程序的性能。而lua是一种脚本语言,可以被嵌入到各种编程语言中,包括redisredistemplateredis的一个Java客户端,可以用于与redis进行交互。redistemplate提供了一个execute方法,用于执行lua脚本执行lua脚本可以有效地提高redis的性能。在执行许多redis命令的情况下,每个命令都需要进行网络延迟,这会对性能产生负面影响。但是,通过执行lua脚本,可以将多个redis命令打包在一起,从而减少网络延迟。此外,lua脚本还可以在服务端执行,从而减少客户端和服务端之间的数据传输量。 使用redistemplate执行lua脚本可以分为以下几步: 1.创建lua脚本执行lua脚本之前,需要创建脚本lua脚本是一段文本,其语法类似于其他脚本语言。在编写脚本时,需要使用redis提供的一些特殊命令,例如get/set等。这些命令与普通的redis命令略有不同,需要使用redis.call或redis.pcall等特殊命令来调用。此外,还可以定义一些函数,从而使脚本更具可读性。 2.使用redistemplate执行脚本 redistemplate提供了execute方法,用于执行lua脚本。execute方法有两个参数:RedisScript对象和RedisSerializer对象。RedisScript对象表示要执行lua脚本,可以使用LuaScriptBuilder类来构建。RedisSerializer对象表示要使用的序列化程序,用于将参数转换为字节数组以及将结果转换回对象。默认情况下,redistemplate使用JdkSerializationRedisSerializer来序列化对象,但也可以使用其他序列化程序,例如Jackson2JsonRedisSerializer。 执行lua脚本的结果是一个Object类型的值,可以通过类型转换将其转换为所需的类型,例如String、List等。此外,还可以使用redis提供的一些命令获取更复杂的结果,例如evalsha命令可以获取lua脚本的SHA1哈希值,从而可以在之后的操作中更高效地使用这个脚本。 总的来说,通过使用redistemplate执行lua脚本,可以在redis中实现更复杂的操作,从而提高应用程序的性能和可靠性。虽然lua脚本相对复杂一些,但学习好后会发现有很多用处。 ### 回答3: redistemplateRedis中的一个模板,在执行Lua脚本时可以使用它来提供更多的功能。 在Redis中使用Lua脚本可以实现一些比较复杂的操作,而redistemplate可以为这些操作提供更好的支持。例如,当需要操作Redis的键和值时,通常需要先对它们进行序列化和反序列化,这个过程比较繁琐,但redistemplate提供了这些操作的封装,使得操作起来更为简单。 使用redistemplate执行Lua脚本时,需要将脚本和参数都传递给redistemplate,然后由redistemplate将它们交给Redis进行执行。在执行完成后,redistemplate会返回脚本执行结果,同时也会释放与此脚本相关的所有资源。 需要注意的是,在使用redistemplate执行Lua脚本时,应该确保脚本的安全性。因为Lua脚本具有比较强的执行能力,如果脚本存在安全漏洞,可能会导致Redis的数据丢失或其他安全问题。因此,在编写和执行Lua脚本时应该遵守最佳安全实践,避免脚本的恶意使用。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值