/src/main/java/com/jieyin/upload/utils/RedisUtils.java
Java | 389 lines | 196 code | 29 blank | 164 comment | 20 complexity | 8b0f7b7ead6ee8984e723efa076ffbbf MD5 | raw file
- /**
- * Copyright (c) 2016-2019 人人开源 All rights reserved.
- * <p>
- * https://www.renren.io
- * <p>
- * 版权所有,侵权必究!
- */
- package com.jieyin.upload.utils;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.connection.RedisConnection;
- import org.springframework.data.redis.connection.RedisConnectionFactory;
- import org.springframework.data.redis.connection.RedisStringCommands;
- import org.springframework.data.redis.connection.ReturnType;
- import org.springframework.data.redis.core.*;
- import org.springframework.data.redis.core.types.Expiration;
- import org.springframework.stereotype.Component;
- import java.io.Serializable;
- import java.nio.charset.Charset;
- import java.util.Date;
- import java.util.List;
- import java.util.Set;
- import java.util.UUID;
- import java.util.concurrent.TimeUnit;
- /**
- * Redis工具类
- *
- * @author Mark sunlightcs@gmail.com
- */
- @Slf4j
- @Component
- public class RedisUtils {
- @Autowired
- private RedisTemplate redisTemplate;
- /**
- * 写入缓存
- *
- * @param key
- * @param value
- * @return
- */
- public boolean set(final String key, Object value) {
- boolean result = false;
- try {
- ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
- operations.set(key, value);
- result = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * 写入缓存设置当前时间
- *
- * @param key
- * @param value
- * @param nowTime
- * @return
- */
- public boolean set(final String key, Object value, Long nowTime) {
- boolean result = false;
- try {
- ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
- operations.set(key, value);
- operations.set(key + "_setTime", String.valueOf(nowTime));
- result = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * 写入缓存设置当前时间
- *
- * @param key
- * @param value
- * @return
- */
- public boolean setNowData(final String key, Object value) {
- Long nowTime = new Date().getTime();
- return set(key, value, nowTime);
- }
- /**
- * 获取缓存
- *
- * @param key
- * @param expireTime
- * @return
- */
- public Object get(final String key, Long expireTime) {
- Object result = null;
- Object setTime;
- Long nowTime = new Date().getTime();
- ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
- setTime = operations.get(key + "_setTime");
- if (setTime != null && nowTime - Long.parseLong(setTime.toString()) < expireTime) {
- result = operations.get(key);
- log.info("从redis中取出的值为:{}",result.toString());
- }
- return result;
- }
- /**
- * 获取缓存(有效期限制)转对象
- *
- * @param key
- * @param expireTime
- * @param clazz
- * @param <T>
- * @return
- */
- public <T> T get(final String key, Long expireTime, Class<T> clazz) {
- Object object = get(key, expireTime);
- if (object == null) {
- return null;
- } else {
- JSONObject jsonObject = JSONObject.parseObject(object.toString());
- return JSON.toJavaObject(jsonObject, clazz);
- }
- }
- /**
- * 写入缓存设置时效时间
- *
- * @param key
- * @param value
- * @return
- */
- public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
- boolean result = false;
- try {
- ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
- operations.set(key, value);
- redisTemplate.expire(key, expireTime, timeUnit);
- result = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * 批量删除对应的value
- *
- * @param keys
- */
- public void remove(final String... keys) {
- for (String key : keys) {
- remove(key);
- }
- }
- /**
- * 批量删除key
- *
- * @param pattern
- */
- public void removePattern(final String pattern) {
- Set<Serializable> keys = redisTemplate.keys(pattern);
- if (keys.size() > 0) {
- redisTemplate.delete(keys);
- }
- }
- /**
- * 删除对应的value
- *
- * @param key
- */
- public void remove(final String key) {
- if (exists(key)) {
- redisTemplate.delete(key);
- }
- }
- /**
- * 判断缓存中是否有对应的value
- *
- * @param key
- * @return
- */
- public boolean exists(final String key) {
- return redisTemplate.hasKey(key);
- }
- /**
- * 读取缓存
- *
- * @param key
- * @return
- */
- public Object get(final String key) {
- Object result = null;
- ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
- result = operations.get(key);
- return result;
- }
- /**
- * 哈希 添加
- *
- * @param key
- * @param hashKey
- * @param value
- */
- public void hmSet(String key, Object hashKey, Object value) {
- HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
- hash.put(key, hashKey, value);
- }
- /**
- * 哈希获取数据
- *
- * @param key
- * @param hashKey
- * @return
- */
- public Object hmGet(String key, Object hashKey) {
- HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
- return hash.get(key, hashKey);
- }
- /**
- * 列表添加
- *
- * @param k
- * @param v
- */
- public void lPush(String k, Object v) {
- ListOperations<String, Object> list = redisTemplate.opsForList();
- list.rightPush(k, v);
- }
- /**
- * 列表获取
- *
- * @param k
- * @param l
- * @param l1
- * @return
- */
- public List<Object> lRange(String k, long l, long l1) {
- ListOperations<String, Object> list = redisTemplate.opsForList();
- return list.range(k, l, l1);
- }
- /**
- * 集合添加
- *
- * @param key
- * @param value
- */
- public void add(String key, Object value) {
- SetOperations<String, Object> set = redisTemplate.opsForSet();
- set.add(key, value);
- }
- /**
- * 集合获取
- *
- * @param key
- * @return
- */
- public Set<Object> setMembers(String key) {
- SetOperations<String, Object> set = redisTemplate.opsForSet();
- return set.members(key);
- }
- /**
- * 有序集合添加
- *
- * @param key
- * @param value
- * @param scoure
- */
- public void zAdd(String key, Object value, double scoure) {
- ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
- zset.add(key, value, scoure);
- }
- /**
- * 有序集合获取
- *
- * @param key
- * @param scoure
- * @param scoure1
- * @return
- */
- public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
- ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
- return zset.rangeByScore(key, scoure, scoure1);
- }
- /**
- * 解锁脚本,原子操作
- */
- private static final String unlockScript =
- "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n"
- + "then\n"
- + " return redis.call(\"del\",KEYS[1])\n"
- + "else\n"
- + " return 0\n"
- + "end";
- /**
- * 加锁,有阻塞
- *
- * @param name
- * @param expire
- * @param timeout
- * @return
- */
- public String lock(String name, long expire, long timeout) {
- long startTime = System.currentTimeMillis();
- String token;
- do {
- token = tryLock(name, expire);
- if (token == null) {
- if ((System.currentTimeMillis() - startTime) > (timeout - 50))
- break;
- try {
- Thread.sleep(50); //try 50 per sec
- } catch (InterruptedException e) {
- e.printStackTrace();
- return null;
- }
- }
- } while (token == null);
- return token;
- }
- /**
- * 加锁,无阻塞
- *
- * @param name
- * @param expire
- * @return
- */
- public String tryLock(String name, long expire) {
- String token = UUID.randomUUID().toString();
- RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
- RedisConnection conn = factory.getConnection();
- try {
- Boolean result = conn.set(name.getBytes(Charset.forName("UTF-8")), token.getBytes(Charset.forName("UTF-8")),
- Expiration.from(expire, TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT);
- if (result != null && result)
- return token;
- } finally {
- RedisConnectionUtils.releaseConnection(conn, factory);
- }
- return null;
- }
- /**
- * 解锁
- *
- * @param name
- * @param token
- * @return
- */
- public boolean unlock(String name, String token) {
- byte[][] keysAndArgs = new byte[2][];
- keysAndArgs[0] = name.getBytes(Charset.forName("UTF-8"));
- keysAndArgs[1] = token.getBytes(Charset.forName("UTF-8"));
- RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
- RedisConnection conn = factory.getConnection();
- try {
- Long result = conn.scriptingCommands().eval(unlockScript.getBytes(Charset.forName("UTF-8")), ReturnType.INTEGER, 1, keysAndArgs);
- if (result != null && result > 0)
- return true;
- } finally {
- RedisConnectionUtils.releaseConnection(conn, factory);
- }
- return false;
- }
- }