下面列出了org.springframework.web.servlet.handler.HandlerInterceptorAdapter#redis.clients.jedis.JedisCommands 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void addActiveNum(Integer userId,double score){
int month = DateUtil.thisMonth()+1;
String key = CommonConstant.FQ_ACTIVE_USER_SORT+month;
try {
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
Double scoreStore = commands.zscore(key,userId.toString());
if(scoreStore == null){
scoreStore = score;
}else {
scoreStore += score;
}
commands.zadd(key,scoreStore,userId.toString());
commands.expire(key,180*24*60*60);
} catch (Exception e) {
logger.error(e);
}finally {
JedisProviderFactory.getJedisProvider(null).release();
}
}
@PostMapping("/manage/add")
@ResponseBody
public BaseResult add(String ip){
BaseResult result = new BaseResult();
try {
if(!Validator.isIpv4(ip)){
result.setResult(ResultEnum.FAIL);
result.setMessage("IP格式不正确!");
return result;
}
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
commands.sadd(CommonConstant.FQ_BLACK_LIST_REDIS_KEY,ip);
} catch (Exception e) {
logger.error("",e);
}finally {
JedisProviderFactory.getJedisProvider(null).release();;
}
return result;
}
@Override
public void clearGroup(final String groupName, final boolean containPkCache) {
String cacheGroupKey = groupName + CacheHandler.GROUPKEY_SUFFIX;
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
try {
Set<String> keys = commands.zrange(cacheGroupKey, 0, -1);
//删除实际的缓存
if (keys != null && keys.size() > 0) {
RedisBatchCommand.removeObjects(keys.toArray(new String[0]));
}
commands.del(cacheGroupKey);
//删除按ID缓存的
if (containPkCache) {
keys = JedisProviderFactory.getMultiKeyCommands(null).keys(groupName + ".id:*");
if (keys != null && keys.size() > 0) {
RedisBatchCommand.removeObjects(keys.toArray(new String[0]));
}
}
} finally {
JedisProviderFactory.getJedisProvider(null).release();
}
}
public Long zrem(final String key, final String... member){
return exec(new RedisCallback<Long>() {
@Override
public Long doCallback(JedisCommands jedis) {
return jedis.zrem(key, member);
}
});
}
public Set<String> zrangeByScore(final String key, final double min, final double max){
return exec(new RedisCallback<Set<String>>() {
@Override
public Set<String> doCallback(JedisCommands jedis) {
return jedis.zrangeByScore(key, min, max);
}
});
}
public Long zrevrank(final String key, final String member){
return exec(new RedisCallback<Long>() {
@Override
public Long doCallback(JedisCommands jedis) {
return jedis.zrank(key, member);
}
});
}
public static void refreshUserCacheByUid(Integer userId){
String cacheKey = "FqUser.id:"+userId;
try {
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
FqUserService fqUserService = SpringUtils.getBean("fqUserServiceImpl");
FqUser fqUser = fqUserService.selectByPrimaryKey(userId);
FqUserCache fqUserCache = new FqUserCache(fqUser);
commands.set(cacheKey,JSON.toJSONString(fqUserCache));
commands.expire(cacheKey,300);
} catch (Exception e) {
logger.error("refreshUserCacheByUid",e);
}finally {
JedisProviderFactory.getJedisProvider(null).release();
}
}
public Set<String> zrevrangeByScore(final String key, final double max, final double min,
final int offset, final int count){
return exec(new RedisCallback<Set<String>>() {
@Override
public Set<String> doCallback(JedisCommands jedis) {
return jedis.zrevrangeByScore(key, min, max, offset, count);
}
});
}
public static void addCollect(String type,Integer uid, Integer thoughtId) {
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
try {
String key = getCollectKey(type,uid);
commands.sadd(key,thoughtId.toString());
commands.expire(key,24*60*60);
} finally{
JedisProviderFactory.getJedisProvider(null).release();
}
}
public static void removeCollect(String type,Integer uid, Integer thoughtId) {
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
try {
String key = getCollectKey(type,uid);
commands.srem(key,thoughtId.toString());
} finally{
JedisProviderFactory.getJedisProvider(null).release();
}
}
public static void refreshCollect(String type,Integer uid,List<Integer> list) {
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
try {
String key = getCollectKey(type,uid);
for(Integer tid : list){
commands.sadd(key, tid.toString());
}
commands.expire(key,24*60*60);
} finally{
JedisProviderFactory.getJedisProvider(null).release();
}
}
/**
* 添加拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptorAdapter() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
//如果不是ajax 代表是点击页面 则统计点击数量
if (null == request.getHeader("X-Requested-With") || !request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
try {
String ip = WebUtil.getIP(request);
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
boolean isBlackIp = commands.sismember(CommonConstant.FQ_BLACK_LIST_REDIS_KEY,ip);
if(isBlackIp){
logger.info("该ip:{} 存在于黑名单,禁止其访问!",ip);
response.sendRedirect(request.getContextPath()+"/blackList/denyService");
return false;
}
String clickkey = CommonConstant.FQ_IP_DATA_THIS_DAY_FORMAT;
Double score = commands.zscore(clickkey,ip);
if(score == null){
commands.zadd(clickkey,1,ip);
}else {
commands.zadd(clickkey,score+1,ip);
}
commands.expire(clickkey,30*24*60*60);//存放一个月
} finally{
JedisProviderFactory.getJedisProvider(null).release();
}
}
return true;
}
}).addPathPatterns("/**").excludePathPatterns("/blackList/denyService");
}
@PostMapping("findActiveUserNames")
@ResponseBody
public Object findActiveUserNames(){
BaseResult result = new BaseResult();
try {int month = DateUtil.thisMonth()+1;
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
String key = "activeUserNames"+month;
Set<String> activeNames = commands.smembers(key);
if(CollectionUtil.isEmpty(activeNames)){
Set<String> userIds =commands.zrevrange(CommonConstant.FQ_ACTIVE_USER_SORT+month,0,9);
if(CollectionUtils.isNotEmpty(userIds)){
List<Integer> userIdList = Lists.newArrayList();
for(String userId : userIds){
userIdList.add(Integer.valueOf(userId));
}
FqUserExample example = new FqUserExample();
example.createCriteria().andIdIn(userIdList);
List<FqUser> fqUsers = fqUserService.selectByExample(example);
List<String> names = fqUsers.stream().map(FqUser::getNickname).collect(Collectors.toList());
result.setData(names);
commands.sadd(key,names.toArray(new String[names.size()]));
commands.expire(key,7*24*60*60);
}
}else {
result.setData(activeNames);
}
} catch (Exception e) {
logger.error("获取活跃用户信息报错",e);
} finally {
JedisProviderFactory.getJedisProvider(null).release();
}
return result;
}
@GetMapping("upLevel")
public String upLevel(Model model){
FqUserCache fqUserCache = getCurrentUser();
int month = DateUtil.thisMonth()+1;
int lastMonth = month == 1? 12 : month-1;
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
Double score = commands.zscore(CommonConstant.FQ_ACTIVE_USER_SORT+month,fqUserCache.getId().toString());
Double lastMonthScore = commands.zscore(CommonConstant.FQ_ACTIVE_USER_SORT+lastMonth,fqUserCache.getId().toString());
Double totolScore = (score == null?0:score)+(lastMonthScore==null?0:lastMonthScore);
model.addAttribute("totolScore",totolScore);
return "/user/upLevel.html";
}
protected <T> T exec0(final JedisCallback<T> callback){
return exec(new RedisCallback<T>() {
@Override
public T doCallback(JedisCommands param) {
return callback.doCallback((Jedis)param);
}
});
}
@ResponseBody
@PostMapping("/record")
public BaseResult record(FqWebsiteDir fqWebsiteDir) {
BaseResult baseResult = new BaseResult();
try {
FqUserCache user = getCurrentUser();
Integer uid = user == null?0:user.getId();
if(StringUtils.isNotEmpty(fqWebsiteDir.getUrl())){
FqWebsiteDirExample example = new FqWebsiteDirExample();
example.createCriteria().andUrlEqualTo(fqWebsiteDir.getUrl()).andDelFlagEqualTo(YesNoEnum.NO.getValue());
FqWebsiteDir fqWebsiteDirDB = fqWebsiteDirService.selectFirstByExample(example);
if(fqWebsiteDirDB != null){
fqWebsiteDirDB.setClickCount(fqWebsiteDirDB.getClickCount() == null?1:fqWebsiteDirDB.getClickCount()+1);
fqWebsiteDirService.updateByPrimaryKey(fqWebsiteDirDB);
if(uid > 0){
//记录某个人的点击网站偏好
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
String key = CommonConstant.FQ_USER_WEBSITE_CLICK_COUNT +":"+uid;
Double scoreStore = commands.zscore(key,fqWebsiteDirDB.getId().toString());
if(scoreStore == null){
scoreStore = 1d;
}else {
scoreStore += 1;
}
commands.zadd(key,scoreStore,fqWebsiteDirDB.getId().toString());
}
}else {
logger.info("数据库未查到对应的url,网址为:{}",fqWebsiteDir.getUrl());
}
}
} catch (Exception e) {
logger.error("记录点击次数报错",e);
}finally {
JedisProviderFactory.getJedisProvider(null).release();
}
return baseResult;
}
@GetMapping("manage")
public String manage(Model model, @RequestParam(required = false) String queryDate){
try {
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
Set<String> ips =commands.smembers(CommonConstant.FQ_BLACK_LIST_REDIS_KEY);
model.addAttribute("ips",ips);
Set<Tuple> tuples = Sets.newHashSet();
String key = "";
if(StringUtils.isNotEmpty(queryDate)){
key = "fq_ip_data_"+queryDate;
tuples = commands.zrevrangeWithScores(key,0,100);
}else {
tuples = commands.zrevrangeWithScores(CommonConstant.FQ_IP_DATA_THIS_DAY_FORMAT,0,100);
}
List<IpVisitDTO> keyValueList = Lists.newArrayList();
tuples.forEach(tuple -> keyValueList.add(new IpVisitDTO(tuple.getElement(),tuple.getScore()+"", CommonUtils.getFullRegionByIp(tuple.getElement()))));
model.addAttribute("visitIps",keyValueList);
model.addAttribute("beauties",CommonConstant.BEAUTY_BANNERS);
} catch (Exception e) {
logger.error("",e);
model.addAttribute("errorMsg","出错了");
return GENERAL_CUSTOM_ERROR_URL;
}finally {
JedisProviderFactory.getJedisProvider(null).release();;
}
return "/blackList/manage.html";
}
@PostMapping("/manage/remove")
@ResponseBody
public BaseResult manageList(String ip){
BaseResult result = new BaseResult();
try {
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
Long id =commands.srem(CommonConstant.FQ_BLACK_LIST_REDIS_KEY,ip);
} catch (Exception e) {
logger.error("",e);
}finally {
JedisProviderFactory.getJedisProvider(null).release();;
}
return result;
}
private boolean setRedis(final String key, final long expire) {
try {
String result = redisTemplate.execute((RedisCallback<String>) connection -> {
JedisCommands commands = (JedisCommands) connection.getNativeConnection();
String uuid = UUID.randomUUID().toString();
lockFlag.set(uuid);
return commands.set(key, uuid, "NX", "PX", expire);
});
return !StringUtils.isEmpty(result);
} catch (Exception e) {
log.error("set redisDistributeLock occured an exception", e);
}
return false;
}
public Set<String> zrangeByIndex(final String key, final long start, final long end){
return exec(new RedisCallback<Set<String>>() {
@Override
public Set<String> doCallback(JedisCommands jedis) {
return jedis.zrange(key, start, end);
}
});
}
@Override
public void putGroup(String cacheGroupKey, String key, long expireSeconds) {
long score = calcScoreInRegionKeysSet(expireSeconds);
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
try {
commands.zadd(cacheGroupKey, score, key);
commands.pexpire(cacheGroupKey, expireSeconds * 1000);
} finally {
JedisProviderFactory.getJedisProvider(null).release();
}
}
@Override
public void removeFromGroup(String cacheGroupKey, String key) {
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
try {
commands.zrem(cacheGroupKey, key);
//
commands.del(key);
} finally {
JedisProviderFactory.getJedisProvider(null).release();
}
}
@Override
public void clearExpiredGroupKeys(String cacheGroup) {
long maxScore = System.currentTimeMillis() / 1000 - this.baseScoreInRegionKeysSet;
JedisCommands commands = JedisProviderFactory.getJedisCommands(null);
try {
commands.zremrangeByScore(cacheGroup, 0, maxScore);
} finally {
JedisProviderFactory.getJedisProvider(null).release();
}
logger.debug("clearExpiredGroupKeys runing:cacheName:{} , score range:0~{}", cacheGroup, maxScore);
}
public Double zscore(final String key, final String member){
return exec(new RedisCallback<Double>() {
@Override
public Double doCallback(JedisCommands jedis) {
return jedis.zscore(key, member);
}
});
}
@Override
public List<String> srandmember(final String key, final Integer count) {
return exec(new RedisCallback<List<String>>() {
@Override
public List<String> doCallback(JedisCommands jedis) {
return jedis.srandmember(key, count);
}
});
}
@Override
public Jedis getJedis() {
JedisCommands _commands = getCommands();
if (_commands instanceof Jedis) {
return (Jedis) _commands;
}
return null;
}
@Override
public Set<String> smembers(final String key) {
return exec(new RedisCallback<Set<String>>() {
@Override
public Set<String> doCallback(JedisCommands jedis) {
return jedis.smembers(key);
}
});
}
@Override
public void release() {
JedisCommands _commands = __jedisCommands.get();
if (_commands != null && !IRedis.ConnectionType.CLUSTER.equals(__dataSourceAdapter.getDataSourceCfgMeta().getConnectionType())) {
if (_commands instanceof Closeable) {
try {
((Closeable) _commands).close();
} catch (IOException e) {
_LOG.warn("An exception occurs when the JedisCommands is released: ", RuntimeUtils.unwrapThrow(e));
}
}
}
__jedisCommands.remove();
}
protected <T> T exec0(final ShardedJedisCallback<T> callback){
return exec(new RedisCallback<T>() {
@Override
public T doCallback(JedisCommands param) {
return callback.doCallback((ShardedJedis)param);
}
});
}
@Override
public Map<String, Float> execute(final JedisCommands client, final SolrParams params) {
final String key = ParamUtil.assertGetStringByName(params, "key");
final long start = ParamUtil.tryGetIntByName(params, "range_start", 0);
final long end = ParamUtil.tryGetIntByName(params, "range_end", -1);
final boolean withScores = ParamUtil.tryGetBooleanByName(params, "with_scores", true);
log.debug("Fetching ZREVRANGE from Redis for key: {} ({}, {})", key, start, end);
if (withScores) {
return ResultUtil.tupleIteratorToMap(client.zrevrangeWithScores(key, start, end));
} else {
return ResultUtil.stringIteratorToMap(client.zrevrange(key, start, end));
}
}