jedis工具类

2019-12-10  本文已影响0人  紫色红色黑色

描述

jedis是redis客户端java实现。jedis不支持多线程操作,是非线程安全的,一般使用jedisPool线程安全的jedis池。

代码

package com.redoor.guava;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.function.Function;

public class RedisCli {


    private static final String host = "127.0.0.1";
    private static final String port = "6379";
    private static final JedisPool jedisPool;


    static {
        jedisPool = new JedisPool(host, Integer.parseInt(port));
    }

    public static String get(String key) {
        Jedis jedis = null;
        String result = null;

        try {
            jedis = jedisPool.getResource();
            result = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

        return result;
    }

    public static String set(String key, String value) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return result;
    }

    public static <R> R command(Function<Jedis, R> function) {

        Jedis jedis = null;
        R r = null;
        try {
            jedis = jedisPool.getResource();
            r = function.apply(jedis);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return r;
    }

    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    public static void returnJedis(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}

引用

https://blog.csdn.net/a67474506/article/details/40660031
https://www.jianshu.com/p/5e4a1f92c88f
https://cloud.tencent.com/developer/article/1011951
https://www.iteye.com/blog/moon-walker-2397962
https://www.programcreek.com/java-api-examples/?api=redis.clients.jedis.Pipeline
https://www.infoq.cn/article/K7dB5AFKI9mr5Ugbs_px

上一篇 下一篇

猜你喜欢

热点阅读