专栏首页工作笔记精华jedis操作Lua脚本测试

jedis操作Lua脚本测试

import static org.hamcrest.CoreMatchers.equalTo;  
   
import java.util.ArrayList;  
import java.util.List;  
   
import org.hamcrest.CoreMatchers;  
import org.hamcrest.Matcher;  
import org.junit.Test;  
   
import redis.clients.jedis.BinaryJedis;  
import redis.clients.jedis.Jedis;  
import redis.clients.jedis.exceptions.JedisConnectionException;  
import redis.clients.jedis.exceptions.JedisDataException;  
import redis.clients.jedis.tests.utils.ClientKillerUtil;  
import redis.clients.util.SafeEncoder;  
   
public class ScriptingCommandsTest extends JedisCommandTestBase {  
   
   
  @SuppressWarnings("unchecked")  
  @Test  
  public void evalMultiBulk() {  
   
    String script = "return {  
KEYS[1],KEYS[2],ARGV[1],ARGV[2],ARGV[3]  
}";  
    List<String> keys = new ArrayList<String>();  
    keys.add("key1");  
    keys.add("key2");  
   
    List<String> args = new ArrayList<String>();  
    args.add("first");  
    args.add("second");  
    args.add("third");  
   
    List<String> response = (List<String>) jedis.eval(script, keys, args);  
   
    assertEquals(5, response.size());  
    assertEquals("key1", response.get(0));  
    assertEquals("key2", response.get(1));  
    assertEquals("first", response.get(2));  
    assertEquals("second", response.get(3));  
    assertEquals("third", response.get(4));  
     
}  
   
  @SuppressWarnings("unchecked")  
  @Test  
  public void evalMultiBulkWithBinaryJedis() {  
   
    String script = "return {  
KEYS[1],KEYS[2],ARGV[1],ARGV[2],ARGV[3]  
}";  
    List<byte[]> keys = new ArrayList<byte[]>();  
    keys.add("key1".getBytes());  
    keys.add("key2".getBytes());  
   
    List<byte[]> args = new ArrayList<byte[]>();  
    args.add("first".getBytes());  
    args.add("second".getBytes());  
    args.add("third".getBytes());  
   
    BinaryJedis binaryJedis = new BinaryJedis(hnp.getHost(), hnp.getPort(), 500);  
    binaryJedis.connect();  
    binaryJedis.auth("foobared");  
   
    List<byte[]> responses = (List<byte[]>) binaryJedis.eval(script.getBytes(), keys, args);  
    assertEquals(5, responses.size());  
    assertEquals("key1", new String(responses.get(0)));  
    assertEquals("key2", new String(responses.get(1)));  
    assertEquals("first", new String(responses.get(2)));  
    assertEquals("second", new String(responses.get(3)));  
    assertEquals("third", new String(responses.get(4)));  
   
    binaryJedis.close();  
     
}  
   
  @Test  
  public void evalBulk() {  
   
    String script = "return KEYS[1]";  
    List<String> keys = new ArrayList<String>();  
    keys.add("key1");  
   
    List<String> args = new ArrayList<String>();  
    args.add("first");  
   
    String response = (String) jedis.eval(script, keys, args);  
   
    assertEquals("key1", response);  
     
}  
   
  @Test  
  public void evalInt() {  
   
    String script = "return 2";  
    List<String> keys = new ArrayList<String>();  
    keys.add("key1");  
   
    Long response = (Long) jedis.eval(script, keys, new ArrayList<String>());  
   
    assertEquals(new Long(2), response);  
     
}  
   
  @Test  
  public void evalNestedLists() {  
   
    String script = "return {  
 {  
KEYS[1]  
} , {  
2  
}   
}";  
    List<?> results = (List<?>) jedis.eval(script, 1, "key1");  
   
    assertThat((List<String>) results.get(0), listWithItem("key1"));  
    assertThat((List<Long>) results.get(1), listWithItem(2L));  
     
}  
   
  @Test  
  public void evalNoArgs() {  
   
    String script = "return KEYS[1]";  
    List<String> keys = new ArrayList<String>();  
    keys.add("key1");  
    String response = (String) jedis.eval(script, keys, new ArrayList<String>());  
   
    assertEquals("key1", response);  
     
}  
   
  @Test  
  public void evalsha() {  
   
    jedis.set("foo", "bar");  
    jedis.eval("return redis.call('get','foo')");  
    String result = (String) jedis.evalsha("6b1bf486c81ceb7edf3c093f4c48582e38c0e791");  
   
    assertEquals("bar", result);  
     
}  
   
  @Test(expected = JedisDataException.class)  
  public void evalshaShaNotFound() {  
   
    jedis.evalsha("ffffffffffffffffffffffffffffffffffffffff");  
     
}  
   
  @Test  
  public void scriptFlush() {  
   
    jedis.set("foo", "bar");  
    jedis.eval("return redis.call('get','foo')");  
    jedis.scriptFlush();  
    assertFalse(jedis.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));  
     
}  
   
  @Test  
  public void scriptExists() {  
   
    jedis.scriptLoad("return redis.call('get','foo')");  
    List<Boolean> exists = jedis.scriptExists("ffffffffffffffffffffffffffffffffffffffff",  
      "6b1bf486c81ceb7edf3c093f4c48582e38c0e791");  
    assertFalse(exists.get(0));  
    assertTrue(exists.get(1));  
     
}  
   
  @Test  
  public void scriptExistsBinary() {  
   
    jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')"));  
    List<Long> exists = jedis.scriptExists(  
      SafeEncoder.encode("ffffffffffffffffffffffffffffffffffffffff"),  
      SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));  
    assertEquals(new Long(0), exists.get(0));  
    assertEquals(new Long(1), exists.get(1));  
     
}  
   
  @Test  
  public void scriptLoad() {  
   
    jedis.scriptLoad("return redis.call('get','foo')");  
    assertTrue(jedis.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));  
     
}  
   
  @Test  
  public void scriptLoadBinary() {  
   
    jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')"));  
    Long exists = jedis  
        .scriptExists(SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));  
    assertEquals((Long) 1L, exists);  
     
}  
   
  @Test  
  public void scriptKill() {  
   
    try {  
   
      jedis.scriptKill();  
       
} catch (JedisDataException e) {  
   
      assertTrue(e.getMessage().contains("No scripts in execution right now."));  
       
}  
     
}  
   
  @Test  
  public void scriptEvalReturnNullValues() {  
   
    jedis.del("key1");  
    jedis.del("key2");  
   
    String script = "return {  
redis.call('hget',KEYS[1],ARGV[1]),redis.call('hget',KEYS[2],ARGV[2])  
}";  
    List<String> results = (List<String>) jedis.eval(script, 2, "key1", "key2", "1", "2");  
    assertEquals(2, results.size());  
    assertNull(results.get(0));  
    assertNull(results.get(1));  
     
}  
   
  @Test  
  public void scriptEvalShaReturnNullValues() {  
   
    jedis.del("key1");  
    jedis.del("key2");  
   
    String script = "return {  
redis.call('hget',KEYS[1],ARGV[1]),redis.call('hget',KEYS[2],ARGV[2])  
}";  
    String sha = jedis.scriptLoad(script);  
    List<String> results = (List<String>) jedis.evalsha(sha, 2, "key1", "key2", "1", "2");  
    assertEquals(2, results.size());  
    assertNull(results.get(0));  
    assertNull(results.get(1));  
     
}  
   
  @Test  
  public void scriptExistsWithBrokenConnection() {  
   
    Jedis deadClient = new Jedis(jedis.getClient().getHost(), jedis.getClient().getPort());  
    deadClient.auth("foobared");  
   
    deadClient.clientSetname("DEAD");  
   
    ClientKillerUtil.killClient(deadClient, "DEAD");  
   
    // sure, script doesn't exist, but it's just for checking connection  
    try {  
   
      deadClient.scriptExists("abcdefg");  
       
} catch (JedisConnectionException e) {  
   
      // ignore it  
       
}  
   
    assertEquals(true, deadClient.getClient().isBroken());  
   
    deadClient.close();  
     
}  
   
  private <T> Matcher<Iterable<? super T>> listWithItem(T expected) {  
   
    return CoreMatchers.<T> hasItem(equalTo(expected));  
     
}  
   
}  

网友写的抢红包的lua脚本

static String tryGetHongBaoScript =   
//          "local bConsumed = redis.call('hexists', KEYS[3], KEYS[4]);\n"  
//          + "print('bConsumed:' ,bConsumed);\n"  
            "if redis.call('hexists', KEYS[3], KEYS[4]) ~= 0 then\n"  
            + "return nil\n"  
            + "else\n"  
            + "local hongBao = redis.call('rpop', KEYS[1]);\n"  
//          + "print('hongBao:', hongBao);\n"  
            + "if hongBao then\n"  
            + "local x = cjson.decode(hongBao);\n"  
            + "x['userId'] = KEYS[4];\n"  
            + "local re = cjson.encode(x);\n"  
            + "redis.call('hset', KEYS[3], KEYS[4], KEYS[4]);\n"  
            + "redis.call('lpush', KEYS[2], re);\n"  
            + "return re;\n"  
            + "end\n"  
            + "end\n"  
            + "return nil";  

看起来不可思议,这种适合先load,然后用evalsha方法

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • JS之clientX,clientY,screenX,screenY,offsetX,offsetY区别测试

    首先需要知道clientX,clientY,screenX,screenY,offsetX,offsetY 是鼠标事件对象下的几个属性.

    stys35
  • 使用JDK开发WebService 转

      1、定义一个interface,使用@WebService注解标注接口,使用@WebMethod注解标注接口中定义的所有方法,如下所示:

    stys35
  • 聊聊flink的Table API及SQL Programs

    (adsbygoogle = window.adsbygoogle || []).push({});

    stys35
  • Spring Boot 中使用 Kafka

    Kafka 是一种高吞吐的分布式发布订阅消息系统,能够替代传统的消息队列用于解耦合数据处理,缓存未处理消息等,同时具有更高的吞吐率,支持分区、多副本、冗余,因此...

    搜云库
  • Scala Reflection - Mirrors,ClassTag,TypeTag and WeakTypeTag

        反射reflection是程序对自身的检查、验证甚至代码修改功能。反射可以通过它的Reify功能来实时自动构建生成静态的Scala实例如:类(class...

    用户1150956
  • 【一周简报】支付聚合SDK公司Ping++获得千万美元B轮融资,宽带资本领投

    编辑导语 智选SDK一周资讯大事记,将会为您呈现过去一周最受欢迎的SDK资讯、投融资、企业活动、人物访谈和创业故事等信息,让您在最短的时间内了解最火 BeeCl...

    BestSDK
  • RedisPool操作Redis,工具类实例

    redis.properties 配置文件内容 redis.pool.maxActive=100 redis.pool.maxIdle=20 redis.poo...

    生活创客
  • webgl实现径向模糊

    径向模糊,是一种从中心向外呈幅射状,逐渐模糊的效果。 因此径向模糊经常会产生一些中心的发散效果,在PS中同样也有径向模糊的滤镜效果。 径向模糊通常也称为变焦模糊...

    用户3158888
  • 英特尔Movidius推神经计算棒,可在终端运行神经网络

    翻译 | AI科技大本营(rgznai100) 参与 | 周翔 日前,英特尔旗下公司Movidius刚刚推出了一款全新产品:一个能让开发者和研究人员在终端设备部...

    AI科技大本营
  • Redis-KV数据库Java连接以及Jedis包的使用

    描述:Redis是一个开源的Key-Value数据缓存,和Memcached类似。现在基本上主流的语言都有客户端支持,比如java、C、C#、C++、php、N...

    WeiyiGeek

扫码关注云+社区

领取腾讯云代金券