1,接口
/**
* 优先从缓存中查询会员信息
* @param custNum
* @return
*/
public Member findMemberByCustNumFristByRedis(String custNum);
2.实现类
@Override
public Member findMemberByCustNumFristByRedis(String custNum) {
if (StringUtil.isEmpty(custNum)) {// 当传入为空时直接返回为空,会员编号必须存在
return null;
}
Member member = (Member)ShardedJedisUtil.getObj(RedisConst.QUERY_MEMBER_BY_CUSTNUM + custNum);
if (member == null) {
Map<String, Object> parameter = new HashMap<String, Object>();
parameter.put("custNum", custNum);
List<Member> members = this.findList(parameter, null);
if (null != members && !members.isEmpty()) {
ShardedJedisUtil.setObjEx(RedisConst.QUERY_MEMBER_BY_CUSTNUM + custNum, RedisConst.ONE_HOUR_SECONDS, members.get(0));
return members.get(0);
}
}
return member;
}
3.redis操作的工具类
public class ShardedJedisUtil {
final static Logger logger = LoggerFactory.getLogger(ShardedJedisUtil.class);
protected static ShardedJedisClientImpl shardedJedisClient = null;
static {
// 加载SCM平台的redis.conf配置信息,创建客户端对象
logger.info("----------------加载SCM平台的redis.conf配置信息,创建ShardedJedisClientImpl客户端对象--------------");
try {
shardedJedisClient = new ShardedJedisClientImpl("redis.conf");
logger.info("----------------创建ShardedJedisClientImpl客户端对象结束--------------");
} catch (Exception e) {
logger.error("--------创建shardedJedisClient异常,请确认配置是否正确!--------------------", e);
shardedJedisClient = null;
}
}
/**
* 设置字符串类型的键对应的对象到redis中,用户保存对象
*
* @param key 键
* @param seconds 秒 ;在redis中缓存的时间
* @param value 值
* @return
*/
public static Object setObjEx(final String key, final int seconds, final Object value) {
if (null == shardedJedisClient) {
return null;
}
return shardedJedisClient.execute(new ShardedJedisAction<Object>() {
@Override
public String doAction(ShardedJedis shardedJedis) {
byte[] keyBytes = ObjectCopyUtil.objectToByte(key);
byte[] valueBytes = ObjectCopyUtil.objectToByte(value);
return shardedJedis.setex(keyBytes, seconds, valueBytes);
}
});
}
/**
* 根据key获取Redis中保存的对象
*
* @param key 键
* @return
*/
public static Object getObj(final String key) {
if (null == shardedJedisClient) {
return null;
}
return shardedJedisClient.execute(new ShardedJedisAction<Object>() {
@Override
public Object doAction(ShardedJedis shardedJedis) {
byte[] keyBytes = ObjectCopyUtil.objectToByte(key);
byte[] valueBytes = shardedJedis.get(keyBytes);
return ObjectCopyUtil.byteToObject(valueBytes);
}
});
}
}
4.相关的常量类
public class RedisConst {
/** 一分钟的秒数 */
public static final int ONE_MINUTE_SECONDS = 60;
/** 一小时的秒数 */
public static final int ONE_HOUR_SECONDS = 60 * 60;
/** 四小时的秒数 */
public static final int FOUR_HOUR_SECONDS = 60 * 60 * 4;
/** 一天的秒数 */
public static final int ONE_DAY_SECONDS = 60 * 60 * 24;
/** 一个月的秒数 */
public static final int ONE_MONTH_SECONDS = 60 * 60 * 24 * 30;
/*** 通过会员编码查询会员信息 */
public static final String QUERY_MEMBER_BY_CUSTNUM = "queryMemberByCustNum";
}