Commit 36b0b886 by hy

集成common-redis模块

parent 38dfa77b
......@@ -79,6 +79,10 @@
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
......
package cn.datax.common.redis.config;
import cn.datax.common.redis.service.DistributedLock;
import cn.datax.common.redis.service.RedisService;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@ConditionalOnClass(RedisOperations.class)
public class RedisConfig {
/**
* 自定义redis序列化的机制,重新定义一个ObjectMapper.防止和MVC的冲突
*
* @return
*/
@Bean
public RedisSerializer<Object> redisSerializer() {
ObjectMapper objectMapper = new ObjectMapper();
// null数据不返回
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//反序列化时候遇到不匹配的属性并不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//序列化时候遇到空对象不抛出异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//反序列化的时候如果是无效子类型,不抛出异常
objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
//不使用默认的dateTime进行序列化,
objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
//使用JSR310提供的序列化类,里面包含了大量的JDK8时间序列化类
objectMapper.registerModule(new JavaTimeModule());
//启用反序列化所需的类型信息,在属性中添加@class
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
//配置null值的序列化器
GenericJackson2JsonRedisSerializer.registerNullValueSerializer(objectMapper, null);
return new GenericJackson2JsonRedisSerializer(objectMapper);
}
/**
* 实例化 RedisTemplate 对象
*
* @return
*/
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory, RedisSerializer<Object> redisSerializer) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setDefaultSerializer(redisSerializer);
redisTemplate.setValueSerializer(redisSerializer);
redisTemplate.setHashValueSerializer(redisSerializer);
redisTemplate.setKeySerializer(StringRedisSerializer.UTF_8);
redisTemplate.setHashKeySerializer(StringRedisSerializer.UTF_8);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
@ConditionalOnBean(name = "redisTemplate")
public RedisService redisService() {
return new RedisService();
}
@Bean
@ConditionalOnBean(name = "redisTemplate")
public DistributedLock distributedLock() {
return new DistributedLock();
}
}
\ No newline at end of file
package cn.datax.common.redis.serializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.io.*;
public class DataRedisSerializer implements RedisSerializer<Object> {
@Override
public byte[] serialize(Object o) throws SerializationException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(byteOut);
objOut.writeObject(o);
} catch (IOException e) {
e.printStackTrace();
}
return byteOut.toByteArray();
}
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
if (bytes == null) {
return null;
}
ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
ObjectInputStream objIn;
Object obj;
try {
objIn = new ObjectInputStream(byteIn);
obj = objIn.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return obj;
}
}
package cn.datax.common.redis.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/**
* redis分布式锁
*/
@Slf4j
public class DistributedLock {
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 加锁,无阻塞
* @param lock
* @param key
* @param expireTime 锁过期时间单位秒
* @return
*/
public boolean tryLock(String lock, String key, Long expireTime) {
return this.tryLock(lock, key, expireTime, TimeUnit.SECONDS);
}
/**
* 加锁,无阻塞
* @param lock
* @param key
* @param expireTime 锁过期时间
* @param timeUnit
* @return
*/
public boolean tryLock(String lock, String key, Long expireTime, TimeUnit timeUnit) {
Boolean success = redisTemplate.opsForValue().setIfAbsent(lock, key, expireTime, timeUnit);
if (success == null || !success) {
log.info("申请锁(" + lock + "," + key + ")失败");
return false;
}
log.error("申请锁(" + lock + "," + key + ")成功");
return true;
}
public void unlock(String lock, String key) {
String script = "if redis.call('get', KEYS[1]) == KEYS[2] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Long result = redisTemplate.execute(redisScript, Arrays.asList(lock, key));
if (result == null || result == 0) {
log.info("释放锁(" + lock + "," + key + ")失败,该锁不存在或锁已经过期");
} else {
log.info("释放锁(" + lock + "," + key + ")成功");
}
}
}
......@@ -3,4 +3,5 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.datax.common.config.RestTemplateConfig,\
cn.datax.common.exception.GlobalExceptionHandler,\
cn.datax.common.utils.SpringContextHolder,\
cn.datax.common.database.datasource.CacheDataSourceFactoryBean
cn.datax.common.database.datasource.CacheDataSourceFactoryBean,\
cn.datax.common.redis.config.RedisConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment