您的位置:首页 > 数据库 > Redis

获取redis连接服务

2016-07-30 14:54 441 查看
1.先下载redis.clients.jedis.Jedis jar包

import java.util.Set;

import redis.clients.jedis.Jedis;

public class RedisUtil {
private static Jedis jedis;  

    private static final String PREFIX = "redis-";  

    private static final String HOST_IP = "127.0.0.1";  

    private static final int HOST_PORT = 6379;  

 

    public synchronized static Jedis getJedis(String host_ip, int host_port) {  

        jedis = new Jedis(host_ip, host_port);  

        //jedis.auth("root");  //开启密码验证(配置文件中为 requirepass root)的时候需要执行该方法  

  

        return jedis;  

    }  

  

    public synchronized static Jedis getDefaultJedis() {  

        return getJedis(HOST_IP, HOST_PORT);  

    }  

  

    /** 

     *  清空 redis 中的所有数据 

     * */  

    public String flushRedis() {  

        return getDefaultJedis().flushDB();  

    }  

  

    /** 

     *  根据 pattern 获取 redis 中的键 

     * */  

    public Set<String> getKeysByPattern(String pattern) {  

        return getDefaultJedis().keys(pattern);  

    }  

  

    /** 

     *  获取 redis 中所有的键 

     * */  

    public Set<String> getAllKeys() {  

        return getKeysByPattern("*");  

    }  

  

    /** 

     *  判断key是否存在redis中 

     * */  

    public boolean exists(String key) throws Exception {  

        if (StringUtil.IsEmpty(key)) {  

            throw new Exception("key is null");  

        }  

        return getDefaultJedis().exists(PREFIX + key);  

    }  

  

    /** 

     *  从Redis中移除一个key 

     * */  

    public void removeKey(String key) throws Exception {  

        if (StringUtil.IsEmpty(key)) {  

            throw new Exception("key is null");  

        }  

        getDefaultJedis().del(PREFIX + key);  

    }

    

    public static void main (String []args){

    Jedis jedis = getDefaultJedis();  

    System.out.println("jedis is:"+jedis);

   

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: