redis连接池工具类

public class RedisUtil {


    private static JedisPool pool = null;


    /**

     * @功能:带参数的构造函数

     * @参数:host,主机名或主机IP

     * @参数:port,端口

     * @参数:password,访问Redis数据库的密码

     */

    public RedisUtil() {

        if (pool == null) {

            JedisPoolConfig config = new JedisPoolConfig();

            // 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;

            // 如果赋值为-1,则表示不限制;如果pool已经分配了maxTotal个jedis实例,则此时pool的状态为exhausted(耗尽)。

            try {
            config.setMaxActive(300);
            config.setMaxIdle(10);
            config.setTestOnBorrow(true);
            config.setMaxWait(1000 * 100);

            pool = new JedisPool(config, "127.0.0.1");

            } catch (Exception e) {
                    e.printStackTrace();
                    config.setMaxActive(300);
                    config.setMaxIdle(10);
                    config.setTestOnBorrow(true);
                    config.setMaxWait(1000 * 100);
                    pool = new JedisPool(config, "127.0.0.1");
            }

        }

    }


    /**

     * @功能:通过Redis的key获取值,并释放连接资源

     * @参数:key,键值

     * @返回: 成功返回value,失败返回null

     */
    public void kill(){
        pool.destroy();
    }

    public String get(String key){

        Jedis jedis = null;

        String value = null;

        try {

            jedis = pool.getResource();

            value = jedis.get(key);

        }
        catch (Exception e) {

            pool.returnBrokenResource(jedis);
            e.printStackTrace();

        } finally {

            if(null != pool) {

                pool.returnResource(jedis);

            }

        }

        return value;

    }
    
    /**
     * 返还到连接池
     *
     * @param pool
     * @param redis
     */
    public static void returnResource(Jedis redis) {
        if (redis != null) {
            pool.returnResource(redis);
        }
    }

    public byte[] getByte(byte[] key){

        Jedis jedis = null;


        try {

            jedis = pool.getResource();

            return jedis.get(key);

        }
        catch (Exception e) {

            pool.returnBrokenResource(jedis);
            e.printStackTrace();

        } finally {

            if(null != pool) {

                pool.returnResource(jedis);

            }

        }
        return key;


    }


    /**

     * @功能:向redis存入key和value(如果key已经存在 则覆盖),并释放连接资源

     * @参数:key,键

     * @参数:value,与key对应的值

     * @返回:成功返回“OK”,失败返回“0”

     */

    public String set(String key,String value){

        Jedis jedis = null;

        try {

            jedis = pool.getResource();

            return jedis.set(key, value);

        } catch (Exception e) {

            pool.returnBrokenResource(jedis);
            e.printStackTrace();

            return "0";

        } finally {

            if(null != pool) {

                pool.returnResource(jedis);

            }

        }

    }
    
    public static Jedis getJedis(){
        return pool.getResource();
    }
    
    public void setByte(byte[] key,byte[] value){

        Jedis jedis = null;

        try {

            jedis = pool.getResource();

            jedis.set(key, value);

        } catch (Exception e) {

            pool.returnBrokenResource(jedis);
            e.printStackTrace();


        } finally {

            if(null != pool) {

                pool.returnResource(jedis);

            }

        }

    }

    public void remove(String key){

        Jedis jedis = null;

        try {

            jedis = pool.getResource();

            jedis.del(key);

        }
        catch (Exception e) {

            pool.returnBrokenResource(jedis);

            e.printStackTrace();

        } finally {

            if(null != pool) {

                pool.returnResource(jedis);

            }

        }

    }

    public void expire(String key,int seconds){
         Jedis jedis = null;
         try {

             jedis = pool.getResource();

             jedis.expire(key, seconds);

         } catch (Exception e) {
             pool.returnBrokenResource(jedis);
             e.printStackTrace();
         } finally {
             if(null != pool) {
                 pool.returnResource(jedis);
             }
         }


    }

    public Boolean exits(String key){
        if(key==null) return false;
        Jedis jedis = null;

        try {

            jedis = pool.getResource();

             return jedis.exists(key);

        } catch (Exception e) {

            pool.returnBrokenResource(jedis);

            e.printStackTrace();
            return false;

        } finally {

            if(null != pool) {

                pool.returnResource(jedis);

            }

        }

    }
    public void lpush(String key,Map<String, String> map){
         Jedis jedis = null;
         try {
           jedis = pool.getResource();
           jedis.hmset(key, map);
         }catch (Exception e) {
            e.printStackTrace();
        }

    }

    public Long hlen(String key) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hlen(key);
        } catch (Exception e) {
            return null;
        }

    }

    public Set<String> hkeys(String key) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hkeys(key);
        } catch (Exception e) {
            return null;
        }

    }

    public Set<String> hvals(String key) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hkeys(key);

        } catch (Exception e) {
            return null;
        }

    }
    public List<String> hmget(String key,String... fields){
         Jedis jedis = null;
         try {
           jedis = pool.getResource();
           return jedis.hmget(key, fields);

         }catch (Exception e) {
             return null;
         }

    }
    public void hdel(String key,String fields){
        Jedis jedis = null;
        try {
           jedis = pool.getResource();
           jedis.hdel(key, fields);
        }catch (Exception e) {
            // TODO: handle exception
        }
   }
//    @Test
//    public void test4(){
//           SystemWebSocketHandler socket=new SystemWebSocketHandler();
//           JSONObject msg=new JSONObject();
//           msg.put("msg", 3000);
//           msg.put("type", 1);
//           TextMessage message=new TextMessage(msg.toString());
//           socket.sendMessageToMerch("9999999", message);
//    }
    public void test5() {
        RedisUtil jedis=new RedisUtil();
        Map<String, String> map = new HashMap<String, String>();
        JSONObject json=new JSONObject();
        json.put("merchId", 9999999);
        map.put("9999999", json.toString());
        jedis.lpush("pc_order", map);
    }
//    @Test
    public void test3() {
        RedisUtil jedis=new RedisUtil();
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "fujianchao");
        map.put("password", "123");
        map.put("age", "12");
        // 存入一个map
        jedis.lpush("user", map);
        // map key的个数
        System.out.println("map的key的个数" + jedis.hlen("user"));
        // map key
        System.out.println("map的key" + jedis.hkeys("user"));
        // map value
        System.out.println("map的value" + jedis.hvals("user"));
        // (String key, String... fields)返回值是一个list
        List<String> list = jedis.hmget("user", "age", "name");
        System.out.println("redis中key的各个 fields值:"
                + jedis.hmget("user", "age", "name") + list.size());
        // 删除map中的某一个键 的值 password
        // 当然 (key, fields) 也可以是多个fields
        jedis.hdel("user", "age");
        System.out.println("删除后map的key" + jedis.hkeys("user"));
  }
//    @Test
//    public void test5() {
//      RedisUtil jedis=new RedisUtil();
//      Member user = new Member();
//      user.setUserId(12345);
//      // 存入一个 user对象
//      jedis.setByte("user".getBytes(), SerializationUtil.serialize(user));
//      // 获取
//      byte[] bs = jedis.getByte("user".getBytes());
//      Member desUser = (Member) SerializationUtil.deserialize(bs);
//      System.out.println(desUser.getUserId());
//    }

猜你喜欢

转载自blog.csdn.net/qw463800202/article/details/54612586