一、集群配置
application.properties配置redis集群
spring.redis.cluster.nodes=192.168.140.151:7000,192.168.140.151:7001,192.168.140.151:7002,192.168.140.151:7003,192.168.140.151:7004,192.168.140.151:7005
二、序列化,防止key值出现\xac\xed\x00\x05t\x00\x04
@Autowired private RedisTemplate redisTemplate; @PostConstruct public void redisTemplate() { redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new JdkSerializationRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.setHashKeySerializer(new JdkSerializationRedisSerializer()); }
三、分布式锁
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.concurrent.TimeUnit; @Component public class DistributedLock { private static final long timeOut=30; private static long goInMethodTime; @Autowired RedisTemplate redisTemplate; /** *获取分布式锁 */ public synchronized <T> Boolean lock(String key,T value){ goInMethodTime=System.currentTimeMillis(); //如果方法执行时间-当前时间>超时时间则结束,否则继续获取锁 long nowTime=System.currentTimeMillis(); if(nowTime-goInMethodTime<timeOut){ Object execute = redisTemplate.execute(new RedisCallback() { @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { Boolean aBoolean = connection.setNX(key.getBytes(), Object2Bvalue(value)); redisTemplate.expire(key, 1, TimeUnit.MINUTES); // 超时时间1分钟 return aBoolean; } }); if((Boolean)execute){ redisTemplate.expire(key, 1, TimeUnit.MINUTES); // 超时时间1分钟 return true; } nowTime=System.currentTimeMillis(); } return false; } public <T> void unLock(T key){ redisTemplate.delete(key); } static <T> byte[] Object2Bvalue(T value) { ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); ObjectOutputStream objectInputStream = null; try { objectInputStream = new ObjectOutputStream(byteArrayOutputStream); objectInputStream.writeObject(value); } catch (IOException e) { e.printStackTrace(); } byte[] bytes = byteArrayOutputStream.toByteArray(); return bytes; } }