获取redis连接服务

来源:互联网 发布:gre和托福的区别 知乎 编辑:程序博客网 时间:2024/06/13 05:14

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);
   
    }
}


0 0