Java使用redis_Jedis工具

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bj58.opt.top.config.ConfigManage;
import com.bj58.sfft.utility.config.Path;

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

public class JedisClientPool {
    
    private static JedisPool jedisPool = null;
    private static final  Log log =  LogFactory.getLog(JedisClientPool.class);
    
    
    public static final long PRODUCTID_ZHAOPIN = 100201L;
    
    public static final String KEYSETKEY = "topinfo_showhidelist_ordinary";
    
    public static final String ORDINAR_PR_SHOW = "topinfo_ordinary_";
    
//    public static final String ORDINAR_PR_HIDE = "topinfo_ordinary_hl_";
    
    private static final String redisConfigPath = Path.getCurrentPath() + "/config/redis.properties";
    //本地
//    private static final String redisConfigPath = "D:\\redis.properties";
    
    public static final String REDIS_SEPA = ":";
    
    /**
     * Redis config
     */
    public static String[] HOST_PORT;
//    public static String REDIS_BUFFER_DBFLAG;
//    public static String REDIS_BUFFER_DBFLAG_OK;
//    public static String REDIS_PING_OK;
    public static int REIDS_MAX_ACTIVE;
    public static int REDIS_MAX_IDLE;
    public static long REDIS_MAX_WAITE;
    public static boolean TEST_ON_BORROW;
    public static String REDIS_PASSWORD;
    public static int REDIS_TIMEOUT;
    
    static {
        initRedisConf();
    }

    
    private static void initRedisConf() {
        Properties properties = new Properties();
        InputStream in = null;
        try {
//            in = new FileInputStream(new File(redisConfigPath));
            //更换用reids 配置的缓存
            in = new FileInputStream(new File(ConfigManage.getRedisConfigFilePath()));
            properties.load(in);

            HOST_PORT = properties.getProperty("HOST_PORT").split(REDIS_SEPA);
//            REDIS_SERVER_COUNT = REDIS_HOSTS.length;
//            REDIS_BUFFER_DBFLAG = properties.getProperty("BUFFER_DBFLAG");
//            REDIS_BUFFER_DBFLAG_OK = properties.getProperty("BUFFER_DBFLAG_OK");
//            REDIS_PING_OK = properties.getProperty("PING_OK");
            REIDS_MAX_ACTIVE = Integer.parseInt(properties.getProperty("MAX_ACTIVE"));
            REDIS_MAX_IDLE = Integer.parseInt(properties.getProperty("MAX_IDLE"));
            REDIS_MAX_WAITE = Long.parseLong(properties.getProperty("MAX_WAITE"));
            TEST_ON_BORROW = Boolean.parseBoolean(properties.getProperty("TEST_ON_BORROW"));
            REDIS_PASSWORD = properties.getProperty("PASSWORD");
            REDIS_TIMEOUT = Integer.parseInt(properties.getProperty("TIMEOUT"));
        } catch (Exception e) {
            log.error("Redis config load exception config path: " + redisConfigPath+" ",e);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }
    
    
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxActive(REIDS_MAX_ACTIVE);
            config.setMaxIdle(REDIS_MAX_IDLE);
            config.setMaxWait(REDIS_MAX_WAITE);
            config.setTestOnBorrow(TEST_ON_BORROW);
            if(REDIS_PASSWORD == null || "".equals(REDIS_PASSWORD)){
                jedisPool = new JedisPool(config,HOST_PORT[0],Integer.valueOf(HOST_PORT[1]));
            }else{
                jedisPool = new JedisPool(config, HOST_PORT[0], Integer.valueOf(HOST_PORT[1]),REDIS_TIMEOUT, REDIS_PASSWORD) ;
            }
        } catch (Exception e) {
            log.error("load redis config error, ", e);
        }
    }
    
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
    
    public static void returnJedis(Jedis jedis){
        jedisPool.returnResource(jedis);
    }

}
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bj58.opt.top.utils.Constant;

import redis.clients.jedis.Jedis;


public class JedisOperation {
    
    private static final  Log log =  LogFactory.getLog(JedisClientPool.class);
    
    /** The Constant topStateKey. */
    private static final String userTopKey = "usertopinfos_new_";
    
    public static String getCacheByKey(String key){
        String keyValue=null;
        Jedis jedis = JedisClientPool.getJedis();
        if (jedis == null || key ==null) {
            log.error("getCacheByKey jedis null and key is "+key);
            return keyValue;
        }
        try{
             keyValue = jedis.get(key);
        }catch(Exception e){
            log.error("getCacheByKey key="+key+" from redis error",e);
        }finally{
            JedisClientPool.returnJedis(jedis);
        }
        return keyValue;
    }
    
    public static void  setCacheByKey(String key,String value,int seconds){
        Jedis jedis = JedisClientPool.getJedis();
        if (jedis == null || key ==null || value == null || seconds <0) {
            log.error("setCacheByKey jedis null and key is "+key+" and value="+value+" and expireTime="+seconds);
            return ;
        }
        try{
             jedis.setex(key,seconds ,value);
        }catch(Exception e){
            log.error("setCacheByKey key="+key+" and value="+value+" and expireTime="+seconds+"s from redis error",e);
        }finally{
            JedisClientPool.returnJedis(jedis);
        }
    }
    public static long setCacheNXByKey(String key,String value,int seconds){
        Long result=0L;
        Jedis jedis = JedisClientPool.getJedis();
        if (jedis == null || key ==null || value == null || seconds <0) {
            log.error("setCacheNXByKey jedis null and key is "+key+" and value="+value+" and expireTime="+seconds);
            return result;
        }
        try{
            result=jedis.setnx(key, value);
        }catch(Exception e){
            log.error("setCacheNXByKey key="+key+" and value="+value+" and expireTime="+seconds+"s from redis error",e);
        }finally{
            JedisClientPool.returnJedis(jedis);
        }
        return result;
    }
    public static void  delCacheByKey(String key){
        Jedis jedis = JedisClientPool.getJedis();
        if (jedis == null || key ==null ) {
            log.error("delCacheByKey jedis null and key is "+key);
            return ;
        }
        try{
             jedis.del(key);
        }catch(Exception e){
            log.error("delCacheByKey key="+key+" redis error",e);
        }finally{
            JedisClientPool.returnJedis(jedis);
        }
    }
    
    
    /**
     * 根据userID 获取
     * @param userID
     */
    public static List<Long>  getTopListByUserID(long userID){
        List<Long> topIDs = new ArrayList<Long>();
        Jedis jedis = JedisClientPool.getJedis();
        if (jedis == null) {
            log.error("get jedis null and userid is "+userID);
            return topIDs;
        }
        try{
            String strInfoIDs = jedis.get(userTopKey+userID);
            if(strInfoIDs!=null &&!"".equals(strInfoIDs)){
                String[] datas = strInfoIDs.split(";");
                for(String dataOne:datas){
                    if(dataOne!=null && !"".equals(dataOne)){
                        String[] infoCL = dataOne.split(",");
                        topIDs.add(Long.valueOf(infoCL[0]));
                    }
                }
            }
        }catch(Exception e){
            log.error("get topIDs by uerID from redis error",e);
        }finally{
            JedisClientPool.returnJedis(jedis);
        }
        return topIDs;
    }
    
    
    /**
     * 删除key中的缓存
     * @param userID
     * @throws Exception 
     */
    public static void removeUserTopCache(long userID,long entityID,int cateID,int localID) throws Exception{
        
        Jedis jedis = JedisClientPool.getJedis();
        if (jedis == null) {
            log.error("get jedis null and userid is "+userID+" and infoid is "+entityID);
            return;
        }
        
        try{
            
        
        
        String strInfoIDs = jedis.get(userTopKey+userID);
        if(strInfoIDs != null||"".equals(strInfoIDs)){
//            String strInfoIDs = (String)infosObject;
            log.info(" vipapitest matchcache when removecache key is "+userTopKey+userID +" String is "+ strInfoIDs);
            String[] infoIDs = strInfoIDs.split(";");
            StringBuilder newInfoIDs = new StringBuilder();
            int count = 0;
            String theDatas = entityID+","+cateID+","+localID;
            for(String objInfos : infoIDs){            
                if(!objInfos.equals(theDatas) ){
                    log.info(" vipapitest needkeep when removecache key is "+userTopKey+userID +" infoDatas is " + objInfos);
                    if(count > 0){
                        newInfoIDs.append(";");
                    }                
                    newInfoIDs.append(objInfos);
                    count++;
                }
                else{
                    log.info(" vipapitest matchcache when removecache key is "+userTopKey+userID +" topOne is "+theDatas);
                }
            }
            log.info(" vipapitest matchcache when removecache key is "+userTopKey+userID +" String is : "+ newInfoIDs.toString());
            jedis.del(userTopKey+userID);
            if(newInfoIDs.toString().length() > 0){
                jedis.setex(userTopKey+userID, Constant.EXPIRE_ONE_DAY_SECOND,newInfoIDs.toString());
            }            
        }
        }catch (Exception e) {
            log.error("get if hastop error and the userID is "+userID, e);
        } finally {
            JedisClientPool.returnJedis(jedis);
        }
    }
    
    
    /**
     * 将置顶的信息以用户为key插入缓存,供VIP查询用
     * @param userID
     * @throws Exception 
     */
    public static void setUserTopCache(long entityID, long userID, int cateID, int cityID) throws Exception{
        
        
        Jedis jedis = JedisClientPool.getJedis();
        if (jedis == null) {
            log.error("get jedis null and userid is "+userID+" and infoid is "+entityID);
            return;
        }
        
        try{
            
        
        
        String infoIDs = jedis.get(userTopKey+userID);
        if(infoIDs == null||"".equals(infoIDs)){
            StringBuilder strUseInfos = new StringBuilder();
            log.info(" vipapitest newSet key is "+userTopKey+userID +" topOne is "+entityID+","+cateID+","+cityID);
            strUseInfos.append(entityID);
            strUseInfos.append(",");
            strUseInfos.append(cateID);
            strUseInfos.append(",");
            strUseInfos.append(cityID);
            log.info("after setUserTopCache the string in redis: " + strUseInfos.toString());
            jedis.setex(userTopKey+userID,  Constant.EXPIRE_ONE_DAY_SECOND, strUseInfos.toString());
        }
        else{
//            infoIDs = infosObject;
            log.info(" vipapitest setAdd key is "+userTopKey+userID +" topOne is "+entityID+","+cateID+","+cityID);
            StringBuilder strInsertInfo = new StringBuilder();
            strInsertInfo.append(entityID);
            strInsertInfo.append(",");
            strInsertInfo.append(cateID);
            strInsertInfo.append(",");
            strInsertInfo.append(cityID);    
            
            if(infoIDs.indexOf(strInsertInfo.toString()) < 0){
                StringBuilder strUseInfos = new StringBuilder(infoIDs);
                strUseInfos.append(";");    
                strUseInfos.append(strInsertInfo.toString());
                jedis.setex(userTopKey+userID, Constant.EXPIRE_ONE_DAY_SECOND,strUseInfos.toString());
                log.info("after setUserTopCache the string in redis: " + strUseInfos.toString());
            }else{
                log.info(" the info is exist in redis "+userTopKey+userID +" topOne is "+entityID+","+cateID+","+cityID
                        + "===info in redis :" + infoIDs);
            }            
        }
        }catch (Exception e) {
            log.error("get if hastop error and the userID is "+userID, e);
        } finally {
            JedisClientPool.returnJedis(jedis);
        }
        
    }
    
    /**
     * 判断客户历史上是否曾购买过置顶
     * 若购买过返回购买置顶的时间
     * @return
     */
    public static List<Long> getUserTopList(long userID,List<String> localAndCates){
        Jedis jedis = JedisClientPool.getJedis();
        if (jedis == null) {
            log.error("get jedis null and userid is "+userID);
            return null;
        }
        
        try{
            if(localAndCates == null||localAndCates.isEmpty()){
                return null;
            }
            else{
                List<Long> infoList = new ArrayList<Long>();
                String infosObject;
                try {
                    infosObject = jedis.get(userTopKey+userID);
                    if(infosObject == null ||"".equals(infosObject) )
                    {
                        log.info(" vipapitest cache is null and userid is "+userID);
                        return null;
                    }
                    else{
                        String strInMem = infosObject;
                        log.info(" vipapitest cache is:" + strInMem);
                        String[] topDatas = strInMem.split(";");
                        for(String localCates:localAndCates){
                            String[] localCateData = localCates.split(":");
                            String[] cateDatas = localCateData[1].split(",");
                            for(String cate:cateDatas){
                                 for(String topOne:topDatas){                                 
                                     String[] datas = topOne.split(",");
                                     if(localCateData[0].equals(datas[2])&&cate.equals(datas[1])){
                                         infoList.add(Long.valueOf(datas[0]));
                                         log.info("match vip cache infoid is "+datas[0]+"cate is "+datas[1]+" local is "+localCateData[0]);
                                     }
                                 }
                            }
                        }
                        return infoList;
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    log.info(" failed in redisTool.getUserTopList, errorInfo:" + e.toString());
                }
            }
            return null;
        }catch (Exception e) {
            log.error("get if hastop error and the userID is "+userID, e);
        } finally {
            JedisClientPool.returnJedis(jedis);
        }
        return null;
    }
    
    /**
     * 设置用户置顶记录
     * @param userID
     * @param timeID
     */
    public static void setUserCache(long userID, long timeID){
//        Jedis jedis = JedisClientPool.getJedis();
//        if (jedis == null) {
//            log.error("get jedis null");
//        }
//
//        try {
//            String key = CouponConstant.PREFIX_HASTOP+userID;
//            
//            jedis.set(key, String.valueOf(timeID));
//        } catch (Exception e) {
//            log.error("set user top error", e);
//        } finally {
//            JedisClientPool.returnJedis(jedis);
//        }
    }

}

 

posted @ 2016-03-24 17:20  Java扫地僧  阅读(191)  评论(0)    收藏  举报