Jedis连接代码示例:
    1、引入相关依赖:

    1. <dependency>
    2. <groupId>redis.clients</groupId>
    3. <artifactId>jedis</artifactId>
    4. <version>2.9.0</version>
    5. </dependency>

    访问代码:

    1. public class JedisSingleTest {
    2. public static void main(String[] args) throws IOException {
    3. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    4. jedisPoolConfig.setMaxTotal(20);
    5. jedisPoolConfig.setMaxIdle(10);
    6. jedisPoolConfig.setMinIdle(5);
    7. // timeout,这里既是连接超时又是读写超时,从Jedis 2.8开始有区分connectionTimeout和soTimeout的构造函数
    8. JedisPool jedisPool = new JedisPool(jedisPoolConfig, "192.168.0.60", 6379, 3000, null);
    9. Jedis jedis = null;
    10. try {
    11. //从redis连接池里拿出一个连接执行命令
    12. jedis = jedisPool.getResource();
    13. System.out.println(jedis.set("single", "zhuge"));
    14. System.out.println(jedis.get("single"));
    15. //管道示例
    16. //管道的命令执行方式:cat redis.txt | redis-cli -h 127.0.0.1 -a password - p 6379 --pipe
    17. /*Pipeline pl = jedis.pipelined();
    18. for (int i = 0; i < 10; i++) {
    19. pl.incr("pipelineKey");
    20. pl.set("zhuge" + i, "zhuge");
    21. }
    22. List<Object> results = pl.syncAndReturnAll();
    23. System.out.println(results);*/
    24. //lua脚本模拟一个商品减库存的原子操作
    25. //lua脚本命令执行方式:redis-cli --eval /tmp/test.lua , 10
    26. /*jedis.set("product_count_10016", "15"); //初始化商品10016的库存
    27. String script = " local count = redis.call('get', KEYS[1]) " +
    28. " local a = tonumber(count) " +
    29. " local b = tonumber(ARGV[1]) " +
    30. " if a >= b then " +
    31. " redis.call('set', KEYS[1], a-b) " +
    32. " return 1 " +
    33. " end " +
    34. " return 0 ";
    35. Object obj = jedis.eval(script, Arrays.asList("product_count_10016"), Arrays.asList("10"));
    36. System.out.println(obj);*/
    37. } catch (Exception e) {
    38. e.printStackTrace();
    39. } finally {
    40. //注意这里不是关闭连接,在JedisPool模式下,Jedis会被归还给资源池。
    41. if (jedis != null)
    42. jedis.close();
    43. }
    44. }
    45. }