redis工具类

package com.game.buyu.data;

import java.util.Base64;
import java.util.Map;

import org.apache.log4j.Logger;

import com.game.PbLobbyData;
import com.game.util.WebContextUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;

/**
 * @author yb
 * @version 创建时间:2019年3月16日 下午2:59:33 类说明:redis
 */
public class RedisUtil {
    public static final String WritingInRedis = "writing_in_redis";
    private static final Logger log = Logger.getLogger(RedisUtil.class);
    public static Jedis sIns = null;
    public static String RedisUrl = "xxxx1";
    
    public static Jedis GetIns() {
        log.debug("===new一个redis====");
        if (sIns == null) {
            if (WebContextUtil.getConfigValue("redisUrl").equals("xxxx2")) {
                RedisUrl = WebContextUtil.getConfigValue("redisUrl");
            } else {
                RedisUrl = "xxxx1";
            }
            JedisShardInfo jsi = new JedisShardInfo(RedisUrl, 6379,5000);
            jsi.setPassword("xxxxxx");
            try{
                sIns = new Jedis(jsi);
            }catch (Exception e) {
                log.debug("====redis pin 2==========="+e);
            }
            
        }
        return sIns;
    }
    
    // 拼接查询条件
    public static String GetUsrKey(long uid){
        return new StringBuffer().append("usr_").append(uid).toString();
    }
    
    // 用户封禁,即删除当前的key
    public static void UnFrozeUser(long uid){
        Jedis jedis = RedisUtil.GetIns();
        jedis.del(RedisUtil.GetUsrKey(uid));
    }
    
    // 获取用户数据
    public static PbLobbyData.Usr getRedis(long uid) {
        Jedis jedis = RedisUtil.GetIns();
        String key = "usr_"+uid;
        log.debug("====key值==========="+key);
        boolean a = jedis.exists(key);
        log.debug("key"+a);
        if (a) {
            do {
                long wflag = jedis.hincrBy(key, WritingInRedis, 0);
                log.debug("wflag="+wflag);
                if (wflag > 0) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                Map result = jedis.hgetAll(key);
                String protobuf = result.get("proto_data");
                // 解析protobuf
                PbLobbyData.Usr usrProto = null;
                try {
                    usrProto = PbLobbyData.Usr.parseFrom(Base64.getDecoder().decode(protobuf));
                    return usrProto;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            } while (false);
        } else {
            log.warn("getRedis no usr uid=" + uid);
        }
        return null;
        
    }
}

你可能感兴趣的:(redis工具类)