Redis相关操作工具类

 基础版:

import java.util.concurrent.TimeUnit;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;


/**
 * Redis帮助类
 * 
 * @author aaa
 */
public class RedisCacheUtils implements BeanFactoryAware {

    private static BeanFactory beanFactory = null;

    /**
     * 设置缓存
     * 
     * @param key
     * @param object
     * @param expireTime 秒
     */
    @SuppressWarnings("unchecked")
    public static void set(String key, Object object, long expireTime) {
        RedisTemplate redisTemplate = getRedisTemplate();
        if (!StringUtils.isEmpty(key) && redisTemplate != null && redisTemplate.opsForValue() != null) {
            if (expireTime > 0) {
                redisTemplate.opsForValue().set(key, object, expireTime, TimeUnit.SECONDS);
            }
            else {
                redisTemplate.opsForValue().set(key, object, 86400L, TimeUnit.SECONDS);
            }
        }

    }

    /**
     * 删除缓存
     * 
     * @param key
     */
    @SuppressWarnings("unchecked")
    public static void del(String key) {
        RedisTemplate redisTemplate = getRedisTemplate();
        if (!StringUtils.isEmpty(key) && redisTemplate != null) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 获取缓存
     * 
     * @param key
     * @return
     */
    @SuppressWarnings("unchecked")
    public static  T get(String key, Class clazz) {
        Object obj = null;
        RedisTemplate redisTemplate = getRedisTemplate();
        if (redisTemplate != null && redisTemplate.opsForValue() != null) {
            obj = redisTemplate.opsForValue().get(key);
        }
        if (null != obj) {
            return clazz.cast(obj);
        }
        else {
            return null;
        }
    }

    /**
     * 设置Hash类型缓存
     * 
     * @author aaa
     * @param key
     * @param hashKey
     * @param object
     * @param expireTime
     */
    public static void setH(String key, Object hashKey, Object object, long expireTime) {
        RedisTemplate redisTemplate = getRedisTemplate();
        if (!StringUtils.isEmpty(key) && redisTemplate != null && redisTemplate.opsForHash() != null) {
            redisTemplate.opsForHash().put(key, hashKey, object);
            if (expireTime > 0) {
                redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
            else {
                redisTemplate.expire(key, CacheConstant.REDIS_DEAULT_EXPIRE, TimeUnit.SECONDS);
            }
        }
    }

    /**
     * 设置Hash类型
     * 
     * @param key
     * @param hashKey
     * @param object
     */
    public static void setH(String key, Object hashKey, Object object) {
        RedisTemplate redisTemplate = getRedisTemplate();
        if (!StringUtils.isEmpty(key) && redisTemplate != null && redisTemplate.opsForHash() != null) {
            redisTemplate.opsForHash().put(key, hashKey, object);
        }
    }

    /**
     * 获取Hash类型缓存
     * 
     * @author aaa
     * @param key
     * @param hashKey
     * @param clazz
     */
    @SuppressWarnings("unchecked")
    public static  T getH(String key, Object hashKey, Class clazz) {
        Object obj = null;
        RedisTemplate redisTemplate = getRedisTemplate();
        if (redisTemplate != null && redisTemplate.opsForHash() != null) {
            obj = redisTemplate.opsForHash().get(key, hashKey);
        }
        if (null != obj) {
            return clazz.cast(obj);
        }
        else {
            return null;
        }
    }

    /**
     * 获取Hash类型缓存
     * 
     * @author aaa
     * @param key
     * @param hashKey
     */
    @SuppressWarnings("unchecked")
    public static void delH(String key, Object hashKey) {
        RedisTemplate redisTemplate = getRedisTemplate();
        if (!StringUtils.isEmpty(key) && null != hashKey && redisTemplate != null
                && redisTemplate.opsForHash() != null) {
            redisTemplate.opsForHash().delete(key, hashKey);
        }

    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        RedisCacheUtils.beanFactory = beanFactory;
    }

    public static Object getBean(String bean) {
        if (beanFactory != null) {
            return beanFactory.getBean(bean);
        }
        return null;
    }

    public static RedisTemplate getRedisTemplate() {
        return (RedisTemplate) getBean("redisTemplate");
    }
}

 优化版:

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.lang.NonNull;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 

* redis缓存工具类 *

* * @author aaa */ @Slf4j @NoArgsConstructor(access = AccessLevel.PRIVATE) public class RedisCacheExtUtils implements BeanFactoryAware { private static BeanFactory beanFactory = null; private static final RedisCacheExtUtils INSTANCE = new RedisCacheExtUtils(); public static RedisCacheExtUtils getInstance() { return INSTANCE; } public static boolean hasKey(String key) { return hasKey(key, e -> { throw new RuntimeException(e); }); } public static boolean hasKey(String key, Predicate predicate) { RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate == null) { return false; } try { return redisTemplate.hasKey(key); } catch (Exception e) { return predicate.test(e); } } public static boolean hasKey(String key, String hashKey) { return hasKey(key, hashKey, e -> { throw new RuntimeException(e); }); } public static boolean hasKey(String key, String hashKey, Predicate predicate) { RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate == null) { return false; } try { return redisTemplate.opsForHash().hasKey(key, hashKey); } catch (Exception e) { return predicate.test(e); } } /** * 设置缓存 * * @param key key * @param object object * @param expireTime 秒 */ public static void set(String key, Object object, long expireTime) { set(key, object, expireTime, e -> { throw new RuntimeException(e); }); } public static void set(String key, Object object, long expireTime, Function function) { try { RedisCacheUtils.set(key, object, expireTime); } catch (Exception e) { function.apply(e); } } /** * 删除缓存 * * @param key key */ public static void del(String key) { del(key, e -> { throw new RuntimeException(e); }); } public static void del(String key, Function function) { try { RedisCacheUtils.del(key); } catch (Exception e) { function.apply(e); } } /** * 获取缓存 * * @param key key * @return 值 */ public static T get(String key) { return get(key, e -> { throw new RuntimeException(e); }); } public static T get(String key, Function function) { RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate == null) { return function.apply(null); } try { return redisTemplate.opsForValue().get(key); } catch (Exception e) { return function.apply(e); } } /** * 设置Hash类型缓存 * * @author aaa * @param key key * @param hashKey hashKey * @param object object * @param expireTime expireTime */ public static void setH(String key, String hashKey, T object, long expireTime) { setH(key, hashKey, object, expireTime, e -> { throw new RuntimeException(e); }); } public static void setH(String key, String hashKey, T object, long expireTime, Function function) { try { long actualExpireTime = expireTime > 0 ? expireTime : CacheConstant.REDIS_DEAULT_EXPIRE; RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate != null) { HashOperations hashOperations = redisTemplate.opsForHash(); redisTemplate.execute(new SessionCallback() { @Override public Object execute(@NonNull RedisOperations operations) throws DataAccessException { operations.multi(); hashOperations.put(key, hashKey, object); redisTemplate.expire(key, actualExpireTime, TimeUnit.SECONDS); return operations.exec(); } }); } } catch (Exception e) { function.apply(e); } } /** * 设置Hash类型 * * @param key key * @param hashKey hashKey * @param object object */ public static void setH(String key, String hashKey, Object object) { setH(key, hashKey, object, e -> { throw new RuntimeException(e); }); } public static void setH(String key, String hashKey, Object object, Function function) { try { RedisCacheUtils.setH(key, hashKey, object); } catch (Exception e) { function.apply(e); } } public static void setH(String key, Map map) { setH(key, map, e -> { throw new RuntimeException(e); }); } public static void setH(String key, Map map, Function function) { try { RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate != null) { redisTemplate.opsForHash().putAll(key, map); } } catch (Exception e) { function.apply(e); } } public static void setH(String key, Map map, long expireTime) { setH(key, map, expireTime, e -> { throw new RuntimeException(e); }); } public static void setH(String key, Map map, long expireTime, Function function) { try { RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate != null) { HashOperations hashOperations = redisTemplate.opsForHash(); redisTemplate.execute(new SessionCallback() { @Override public Object execute(@NonNull RedisOperations operations) throws DataAccessException { operations.multi(); hashOperations.putAll(key, map); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); return operations.exec(); } }); } } catch (Exception e) { function.apply(e); } } /** * 获取Hash类型缓存 * * @author aaa * @param key key * @param hashKey hashKey */ public static T getH(String key, String hashKey) { return getH(key, hashKey, e -> { throw new RuntimeException(e); }); } public static T getH(String key, String hashKey, Function function) { RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate == null) { return function.apply(null); } try { HashOperations hashOperations = redisTemplate.opsForHash(); return hashOperations.get(key, hashKey); } catch (Exception e) { log.error("RedisCacheExtUtils.getH error!", e); return function.apply(e); } } public static List getH(String key, Collection hashKeys) { return getH(key, hashKeys, e -> { throw new RuntimeException(e); }); } public static List getH(String key, Collection hashKeys, Function> function) { RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate == null) { return function.apply(null); } try { HashOperations hashOperations = redisTemplate.opsForHash(); return hashOperations.multiGet(key, Arrays.asList(hashKeys.toArray())); } catch (Exception e) { return function.apply(e); } } /** * 获取Hash类型缓存 * * @author aaa * @param key key * @param hashKey hashKey */ public static void delH(String key, String hashKey) { delH(key, hashKey, e -> { throw new RuntimeException(e); }); } public static void delH(String key, String hashKey, Function function) { try { RedisCacheUtils.delH(key, hashKey); } catch (Exception e) { function.apply(e); } } public static T script(String script, List keys, Object... args) { return script(e -> { throw new RuntimeException(e); }, script, keys, args); } @SuppressWarnings("unchecked") public static T script(Function function, String script, List keys, Object... args) { RedisTemplate redisTemplate = getRedisTemplate(); if (redisTemplate == null) { return function.apply(null); } try { return (T) redisTemplate.execute(new DefaultRedisScript<>(script, Object.class), keys, args); } catch (Exception e) { return function.apply(e); } } public static void expire(String key, long expireTime, TimeUnit timeUnit) { expire(key, expireTime, timeUnit, e -> { throw new RuntimeException(e); }); } public static void expire(String key, long expireTime, TimeUnit timeUnit, Function function) { RedisTemplate redisTemplate = RedisCacheUtils.getRedisTemplate(); if (redisTemplate != null) { try { redisTemplate.expire(key, expireTime, timeUnit); } catch (Exception e) { function.apply(e); } } } public static boolean setNX(String key, String value, long expireTime, TimeUnit timeUnit) { return setNX(key, value, expireTime, timeUnit, e -> { throw new RuntimeException(e); }); } public static boolean setNX(String key, String value, long expireTime, TimeUnit timeUnit, Predicate predicate) { RedisTemplate redisTemplate = RedisCacheUtils.getRedisTemplate(); if (redisTemplate == null) { return false; } try { Boolean result = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, timeUnit); return result != null && result; } catch (Exception e) { return predicate.test(e); } } @Override public void setBeanFactory(@NonNull BeanFactory beanFactory) throws BeansException { RedisCacheExtUtils.beanFactory = beanFactory; } public static Object getBean(String bean) { if (beanFactory != null) { return beanFactory.getBean(bean); } return null; } @SuppressWarnings("unchecked") public static RedisTemplate getRedisTemplate() { return (RedisTemplate) getBean("redisTemplate"); } }

优化的点:提供了一个redis连不上,或者执行报错的时候的Function接口给调用方,用来处理缓存异常的时候,提供容错解决办法,比如查数据库、返回默认值等

Redis相关操作工具类_第1张图片

Redis分布式工具类:

package com.zte.crm.iepms.common.util;

import com.google.common.collect.Maps;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Nonnull;
import javax.annotation.PostConstruct;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.function.Predicate;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * redis 分布式锁工具类
 *
 * @author aaa
 * @since 2018/11/2 11:20
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RedisLockUtils implements EnvironmentAware {

    private static final String PARAM_SERVICE_NAME = "spring.application.name";
    private static final RedisLockUtils INSTANCE = new RedisLockUtils();

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockUtils.class);
    private static final ThreadLocal> TARGET_LOCKED = new ThreadLocal<>();
    private static final Map DAEMON_LOCK_MAP = new ConcurrentHashMap<>();

    private static final String UNLOCK_LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    private static final Long RELEASE_SUCCESS = 1L;
    /**
     * 锁超时时间,防止线程在入锁以后,无限的执行等待
     */
    private static final long EXPIRE_MSECS = 60_000;
    /**
     * 锁等待时间,防止线程饥饿
     */
    private static final long TIMEOUT_MSECS = 50_000;
	/**
	 * 默认的锁请求间隔时间
	 */
    private static final int DEFAULT_ACQUIRY_RESOLUTION_MILLIS = 50;

	/** 分布式锁key serviceName:lock:lockTarget */
	private static String LOCK_KEY = "{0}:lock:%s";
	private static Environment environment;

    @PostConstruct
	public void daemonThreadStart() {
		String redisLockPrefix = environment.getProperty("redis.lock.prefix");
		if (!StringUtils.hasText(redisLockPrefix)) {
			redisLockPrefix = environment.getProperty(PARAM_SERVICE_NAME);
		}
		LOCK_KEY = MessageFormat.format(LOCK_KEY, redisLockPrefix);
		// 此处开启一个锁守护线程
		new ScheduledThreadPoolExecutor(1, CommonUtils.getThreadFactory("lock-daemon-thread", true))
				.scheduleWithFixedDelay(() -> {
			Iterator> iterator = DAEMON_LOCK_MAP.entrySet().iterator();
			// 间隔10s检查一下锁持有者与锁标记缓存中的持有者标记是否一致
			while (iterator.hasNext()) {
				Map.Entry entry = iterator.next();
				String lockKey = entry.getKey();
				if (entry.getValue().equals(RedisCacheExtUtils.get(lockKey))) {
					RedisCacheExtUtils.expire(lockKey, EXPIRE_MSECS, MILLISECONDS);
				} else {
					iterator.remove();
				}
			}
		}, 5_000, 10_000, MILLISECONDS);
	}

	public static RedisLockUtils getInstance() {
		return INSTANCE;
	}

	/**
	 * 同一线程加锁解锁
	 *
	 * @param lockTarget 锁目标
	 */
    public static void lock(String lockTarget) {
        lock(lockTarget, e -> {
        	throw new RuntimeException(e);
		});
    }

	/**
	 * 同一线程加锁解锁
	 *
	 * @param lockTarget 锁目标
	 * @param predicate 异常时处理方式
	 */
	public static void lock(String lockTarget, Predicate predicate) {
		doLock(lockTarget, s -> tryLock(s, predicate));
	}

	/**
	 * 可以支持不同线程加锁解锁场景
	 *
	 * @param lockTarget 锁目标
	 * @param requestId 钥匙
	 */
	public static void lock(String lockTarget, String requestId) {
		lock(lockTarget, requestId, e -> {
			throw new RuntimeException(e);
		});

	}

	/**
	 * 可以支持不同线程加锁解锁场景
	 *
	 * @param lockTarget 锁目标
	 * @param requestId 钥匙
	 * @param predicate 异常时处理方式
	 */
	public static void lock(String lockTarget, String requestId, Predicate predicate) {
		doLock(lockTarget, s -> tryLock(s, requestId, predicate));
	}

	/**
	 * 尝试获取redis锁
	 * @param lockTarget lockTarget
	 * @return 获取redis锁是否成功
	 */
	public static boolean tryLock(String lockTarget) {
		return tryLock(lockTarget, e -> {
			throw new RuntimeException(e);
		});
	}

	public static boolean tryLock(String lockTarget, Predicate predicate) {
		return tryLock(lockTarget, EXPIRE_MSECS, predicate);
	}

	/**
	 * 尝试获取redis锁, 并设置锁超时时间
	 *
	 * @param lockTarget lockTarget
	 * @param timeout timeout 毫秒
	 * @return 获取redis锁是否成功
	 */
    public static boolean tryLock(String lockTarget, long timeout) {
		return tryLock(lockTarget, timeout, e -> {
			throw new RuntimeException(e);
		});
	}

	public static boolean tryLock(String lockTarget, long timeout, Predicate predicate) {
		String requestId = getLockTargetRequestId(lockTarget);
		try {
			if (tryLock(lockTarget, requestId, timeout, predicate)) {
				return true;
			}
			clearLockedTarget(lockTarget);
			return false;
		} catch (Exception e) {
			clearLockedTarget(lockTarget);
			throw e;
		}
	}

	public static boolean tryLock(String lockTarget, String requestId) {
    	return tryLock(lockTarget, requestId, e -> {
    		throw new RuntimeException(e);
		});
	}

	public static boolean tryLock(String lockTarget, String requestId, Predicate predicate) {
		return tryLock(lockTarget, requestId, EXPIRE_MSECS, predicate);
	}

	public static boolean tryLock(String lockTarget, String requestId, long timeout) {
		return tryLock(lockTarget, requestId, timeout, e -> {
			throw new RuntimeException(e);
		});
	}

	public static boolean tryLock(String lockTarget, String requestId, long timeout, Predicate predicate) {
		String lockKey = String.format(LOCK_KEY, lockTarget);
		try {
			if (doTryLock(lockKey, requestId, timeout)) {
				// 获取锁成功
				// 将锁标记缓存到锁标记缓存
				DAEMON_LOCK_MAP.put(lockKey, requestId);
				return true;
			}
			return false;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			return predicate.test(e);
		}
	}

	/**
	 * 同一线程解锁
	 *
	 * @param lockTarget lockTarget
	 */
	public static void unLock(String lockTarget) {
		unLock(lockTarget, e -> {
			throw new RuntimeException(e);
		});
	}

	/**
	 * 同一线程解锁
	 *
	 * @param lockTarget lockTarget
	 * @param predicate 异常处理方式
	 */
	public static void unLock(String lockTarget, Predicate predicate) {
		try {
			unLock(lockTarget, getLockTargetRequestId(lockTarget), predicate);
		} finally {
			clearLockedTarget(lockTarget);
		}
	}

	/**
	 * 支持部同线程解锁
	 *
	 * @param lockTarget lockTarget
	 */
	public static void unLock(String lockTarget, String requestId) {
		unLock(lockTarget, requestId, e -> {
			throw new RuntimeException(e);
		});
	}

	public static void unLock(String lockTarget, String requestId, Predicate predicate) {
		String lockKey = String.format(LOCK_KEY, lockTarget);
		List keys = Collections.singletonList(lockKey);
		try {
			Long result = RedisCacheExtUtils.script(UNLOCK_LUA_SCRIPT, keys, requestId);
			if (!RELEASE_SUCCESS.equals(result)) {
				LOGGER.warn("【{}】释放【{}】锁失败", requestId, lockKey);
			} else if (LOGGER.isDebugEnabled()) {
				LOGGER.info("【{}】释放【{}】锁成功", requestId, lockKey);
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			predicate.test(e);
		} finally {
			// 删除本地守护线程缓存锁标记 requestId与DAEMON_LOCK_MAP.get(lockKey)相等时清除
			DAEMON_LOCK_MAP.computeIfPresent(lockKey, (key, old) -> Objects.equals(requestId, old) ? null : old);
		}
	}

	/**
	 * 执行加锁
	 *
	 * @param lockTarget 锁目标
	 * @param tryLockPredicate 尝试加锁方法
	 */
	private static void doLock(String lockTarget, Predicate tryLockPredicate) {
		int timeCost = 0;
		SecureRandom random = new SecureRandom();
		try {
			do {
				if (tryLockPredicate.test(lockTarget)) {
					return;
				}
				/*
				 * 获取锁失败 自旋等待
				 * 延迟50-100毫秒随机事件, 这里使用随机时间可能会好一点,可以防止饥饿进程的出现,即,当同时到达多个进程,
				 * 只会有一个进程获得锁,其他的都用同样的频率进行尝试,后面有来了一些进行,也以同样的频率申请锁,这将可能导致前面来的锁得不到满足.
				 * 使用随机的等待时间可以一定程度上保证公平性
				 */
				int acquiryResolutionMillis = random.nextInt(51) + DEFAULT_ACQUIRY_RESOLUTION_MILLIS;
				Thread.sleep(acquiryResolutionMillis);
				timeCost += acquiryResolutionMillis;
			} while (timeCost < TIMEOUT_MSECS);
		} catch (InterruptedException e) {
			LOGGER.error("=========线程中止失败======");
			Thread.currentThread().interrupt();
		}
		// 获取锁失败并超过获取锁的等待时间 给出服务器繁忙 稍后重试的业务异常
		throw new BusinessException(RetCode.BUSINESSERROR_CODE, SERVER_BUSY_ERROR_MSGID);
	}

	/**
	 * 当前线程获取锁目标钥匙
	 *
	 * @param lockTarget 锁目标
	 * @return 钥匙
	 */
	private static String getLockTargetRequestId(String lockTarget) {
		Map targetLockedMap = TARGET_LOCKED.get();
		if (CollectionUtils.isEmpty(targetLockedMap)) {
			targetLockedMap = Maps.newHashMap();
		}
		String requestId = targetLockedMap.get(lockTarget);
		if (!StringUtils.hasText(requestId)) {
			requestId = StringHelper.getGUID();
			targetLockedMap.put(lockTarget, requestId);
			TARGET_LOCKED.set(targetLockedMap);
		}
		return requestId;
	}

	private static void clearLockedTarget(String lockTarget) {
		Map targetLockedMap = TARGET_LOCKED.get();
		targetLockedMap.remove(lockTarget);
		if (CollectionUtils.isEmpty(targetLockedMap)) {
			TARGET_LOCKED.remove();
		}
	}

	/**
	 * 尝试获取redis锁
	 * @param lockKey lockKey
	 * @param requestId requestId
	 * @return 获取redis锁是否成功
	 */
	private static boolean doTryLock(String lockKey, String requestId, long timeout) {
		return RedisCacheExtUtils.setNX(lockKey, requestId, timeout, MILLISECONDS);
	}

	@Override
	public void setEnvironment(@Nonnull Environment environment) {
		RedisLockUtils.environment = environment;
	}
}

 依赖的StringHelper.getGUID()方法如下:

public class StringHelper {


    public StringHelper() {
    }

    public static String getGUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }
}
private static String LOCK_KEY = "{0}:lock:%s";
MessageFormat.format(LOCK_KEY, redisLockPrefix); // 替换{0}
String lockKey = String.format(LOCK_KEY, lockTarget); // 替换%s

你可能感兴趣的:(redis,java,前端)