【修改】将jeecg字样修改为jero(修改完毕)
This commit is contained in:
+2
-2
@@ -87,7 +87,7 @@ jeecg :
|
||||
#webapp文件路径
|
||||
webapp: D://opt//webapp
|
||||
shiro:
|
||||
excludeUrls: /test/jeecgDemo/demo3,/test/jeecgDemo/redisDemo/**,/category/**,/visual/**,/map/**,/jmreport/bigscreen2/**
|
||||
excludeUrls: /test/JeroDemo/demo3,/test/JeroDemo/redisDemo/**,/category/**,/visual/**,/map/**,/jmreport/bigscreen2/**
|
||||
#阿里云oss存储配置
|
||||
oss:
|
||||
endpoint: oss-cn-beijing.aliyuncs.com
|
||||
@@ -110,7 +110,7 @@ jeecg :
|
||||
file-view-domain: 127.0.0.1:8012
|
||||
# minio文件上传
|
||||
minio:
|
||||
minio_url: http://minio.jeecg.com
|
||||
minio_url: http://minio.jero.com
|
||||
minio_name: ??
|
||||
minio_pass: ??
|
||||
bucketName: otatest
|
||||
+2
-2
@@ -29,7 +29,7 @@ spring:
|
||||
max-request-size: 10MB
|
||||
mail:
|
||||
host: smtp.163.com
|
||||
username: jeecgos@163.com
|
||||
username: test@163.com
|
||||
password: ??
|
||||
properties:
|
||||
mail:
|
||||
@@ -101,7 +101,7 @@ spring:
|
||||
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
|
||||
#mybatis plus 设置
|
||||
mybatis-plus:
|
||||
mapper-locations: classpath*:org/jeecg/modules/**/xml/*Mapper.xml
|
||||
mapper-locations: classpath*:com/jero/modules/**/xml/*Mapper.xml
|
||||
global-config:
|
||||
# 关闭MP3.0自带的banner
|
||||
banner: false
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package com.jero.config;
|
||||
|
||||
import feign.Feign;
|
||||
import feign.Logger;
|
||||
import feign.RequestInterceptor;
|
||||
import feign.codec.Encoder;
|
||||
import feign.form.spring.SpringFormEncoder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.common.constant.CommonConstant;
|
||||
import org.springframework.beans.factory.ObjectFactory;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
|
||||
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
|
||||
import org.springframework.cloud.openfeign.support.SpringEncoder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
|
||||
@ConditionalOnClass(Feign.class)
|
||||
@AutoConfigureBefore(FeignAutoConfiguration.class)
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class FeignConfig {
|
||||
|
||||
@Bean
|
||||
public RequestInterceptor requestInterceptor() {
|
||||
return requestTemplate -> {
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (null != attributes) {
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
log.info("Feign request: {}", request.getRequestURI());
|
||||
// 将token信息放入header中
|
||||
String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
|
||||
if(token==null){
|
||||
token = request.getParameter("token");
|
||||
}
|
||||
log.info("Feign request token: {}", token);
|
||||
requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Feign 客户端的日志记录,默认级别为NONE
|
||||
* Logger.Level 的具体级别如下:
|
||||
* NONE:不记录任何信息
|
||||
* BASIC:仅记录请求方法、URL以及响应状态码和执行时间
|
||||
* HEADERS:除了记录 BASIC级别的信息外,还会记录请求和响应的头信息
|
||||
* FULL:记录所有请求与响应的明细,包括头信息、请求体、元数据
|
||||
*/
|
||||
@Bean
|
||||
Logger.Level feignLoggerLevel() {
|
||||
return Logger.Level.FULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Feign支持文件上传
|
||||
* @param messageConverters
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
@Scope("prototype")
|
||||
public Encoder multipartFormEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
|
||||
return new SpringFormEncoder(new SpringEncoder(messageConverters));
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.jero.starter.cloud.config;
|
||||
|
||||
import feign.Client;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
|
||||
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
|
||||
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class PersonBeanConfiguration {
|
||||
|
||||
/**
|
||||
* 创建FeignClient
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
|
||||
SpringClientFactory clientFactory) {
|
||||
return new LoadBalancerFeignClient(new Client.Default(null, null),
|
||||
cachingFactory, clientFactory);
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.jero.starter.cloud.feign;
|
||||
|
||||
public interface IJeroFeignService {
|
||||
|
||||
<T> T newInstance(Class<T> apiType, String name);
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.jero.starter.cloud.feign.impl;
|
||||
|
||||
import feign.*;
|
||||
import feign.codec.Decoder;
|
||||
import feign.codec.Encoder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.common.constant.CommonConstant;
|
||||
import com.jero.starter.cloud.feign.IJeroFeignService;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
|
||||
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@ConditionalOnClass(Feign.class)
|
||||
@AutoConfigureBefore(FeignAutoConfiguration.class)
|
||||
@Import(FeignClientsConfiguration.class)
|
||||
public class JeroFeignService implements IJeroFeignService {
|
||||
|
||||
|
||||
//Feign 原生构造器
|
||||
Feign.Builder builder;
|
||||
|
||||
//创建构造器
|
||||
public JeroFeignService(Decoder decoder, Encoder encoder, Client client, Contract contract) {
|
||||
this.builder = Feign.builder()
|
||||
.client(client)
|
||||
.encoder(encoder)
|
||||
.decoder(decoder)
|
||||
.contract(contract);
|
||||
|
||||
builder.requestInterceptor(requestTemplate -> {
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (null != attributes) {
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
log.info("Feign request: {}", request.getRequestURI());
|
||||
// 将token信息放入header中
|
||||
String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
|
||||
if(token==null){
|
||||
token = request.getParameter("token");
|
||||
}
|
||||
log.info("Feign request token: {}", token);
|
||||
requestTemplate.header(CommonConstant.X_ACCESS_TOKEN, token);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public <T> T newInstance(Class<T> clientClass, String serviceName) {
|
||||
return builder.target(clientClass, String.format("http://%s/", serviceName));
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.jero.boot.starter.job.config;
|
||||
|
||||
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.boot.starter.job.prop.XxlJobProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 定时任务配置
|
||||
*
|
||||
* @author jeecg
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(value = XxlJobProperties.class)
|
||||
@ConditionalOnProperty(value = "jeecg.xxljob.enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class XxlJobConfiguration {
|
||||
|
||||
|
||||
@Autowired
|
||||
private XxlJobProperties xxlJobProperties;
|
||||
|
||||
//@Bean(initMethod = "start", destroyMethod = "destroy")
|
||||
@Bean
|
||||
@ConditionalOnClass()
|
||||
public XxlJobSpringExecutor xxlJobExecutor() {
|
||||
log.info(">>>>>>>>>>> xxl-job config init.");
|
||||
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
|
||||
xxlJobSpringExecutor.setAdminAddresses(xxlJobProperties.getAdminAddresses());
|
||||
xxlJobSpringExecutor.setAppname(xxlJobProperties.getAppname());
|
||||
xxlJobSpringExecutor.setIp(xxlJobProperties.getIp());
|
||||
xxlJobSpringExecutor.setPort(xxlJobProperties.getPort());
|
||||
xxlJobSpringExecutor.setAccessToken(xxlJobProperties.getAccessToken());
|
||||
xxlJobSpringExecutor.setLogPath(xxlJobProperties.getLogPath());
|
||||
xxlJobSpringExecutor.setLogRetentionDays(xxlJobProperties.getLogRetentionDays());
|
||||
return xxlJobSpringExecutor;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.jero.boot.starter.job.prop;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "jeecg.xxljob")
|
||||
public class XxlJobProperties {
|
||||
|
||||
|
||||
private String adminAddresses;
|
||||
|
||||
|
||||
private String appname;
|
||||
|
||||
|
||||
private String ip;
|
||||
|
||||
|
||||
private int port;
|
||||
|
||||
|
||||
private String accessToken;
|
||||
|
||||
|
||||
private String logPath;
|
||||
|
||||
|
||||
private int logRetentionDays;
|
||||
|
||||
/**
|
||||
* 是否开启xxljob
|
||||
*/
|
||||
private Boolean enable = true;
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.jero.boot.starter.lock.annotation;
|
||||
|
||||
import com.jero.boot.starter.lock.enums.LockModel;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* Redisson分布式锁注解
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Target({ElementType.TYPE, ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@Inherited
|
||||
public @interface DistributedLock {
|
||||
|
||||
/**
|
||||
* 锁的模式:如果不设置,自动模式,当参数只有一个.使用 REENTRANT 参数多个 MULTIPLE
|
||||
*/
|
||||
LockModel lockModel() default LockModel.AUTO;
|
||||
|
||||
/**
|
||||
* 如果keys有多个,如果不设置,则使用 联锁
|
||||
* @return
|
||||
*/
|
||||
String[] lockKey() default {};
|
||||
|
||||
/**
|
||||
* key的静态常量:当key的spel的值是LIST,数组时使用+号连接将会被spel认为这个变量是个字符串,只能产生一把锁,达不到我们的目的,<br />
|
||||
* 而我们如果又需要一个常量的话.这个参数将会在拼接在每个元素的后面
|
||||
* @return
|
||||
*/
|
||||
String keyConstant() default "";
|
||||
|
||||
|
||||
/**
|
||||
* 锁超时时间,默认30000毫秒
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
long expireSeconds() default 30000L;
|
||||
|
||||
/**
|
||||
* 等待加锁超时时间,默认10000毫秒 -1 则表示一直等待
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
long waitTime() default 10000L;
|
||||
|
||||
/**
|
||||
* 未取到锁时提示信息
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
String failMsg() default "获取锁失败,请稍后重试";
|
||||
}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
package com.jero.boot.starter.lock.aspect;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import com.jero.boot.starter.lock.annotation.DistributedLock;
|
||||
import com.jero.boot.starter.lock.enums.LockModel;
|
||||
import org.redisson.RedissonMultiLock;
|
||||
import org.redisson.RedissonRedLock;
|
||||
import org.redisson.api.RLock;
|
||||
import org.redisson.api.RedissonClient;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
|
||||
import org.springframework.expression.EvaluationContext;
|
||||
import org.springframework.expression.Expression;
|
||||
import org.springframework.expression.ExpressionParser;
|
||||
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
||||
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
|
||||
/**
|
||||
* 分布式锁解析器
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Slf4j
|
||||
@Aspect
|
||||
@Component
|
||||
public class DistributedLockHandler {
|
||||
|
||||
|
||||
@Autowired(required = false)
|
||||
private RedissonClient redissonClient;
|
||||
|
||||
/**
|
||||
* 切面环绕通知
|
||||
*
|
||||
* @param joinPoint
|
||||
* @param distributedLock
|
||||
* @return Object
|
||||
*/
|
||||
@SneakyThrows
|
||||
@Around("@annotation(distributedLock)")
|
||||
public Object around(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) {
|
||||
Object obj = null;
|
||||
log.info("进入RedisLock环绕通知...");
|
||||
RLock rLock = getLock(joinPoint, distributedLock);
|
||||
boolean res = false;
|
||||
//获取超时时间
|
||||
long expireSeconds = distributedLock.expireSeconds();
|
||||
//等待多久,n秒内获取不到锁,则直接返回
|
||||
long waitTime = distributedLock.waitTime();
|
||||
//执行aop
|
||||
if (rLock != null) {
|
||||
try {
|
||||
if (waitTime == -1) {
|
||||
res = true;
|
||||
//一直等待加锁
|
||||
rLock.lock(expireSeconds, TimeUnit.MILLISECONDS);
|
||||
} else {
|
||||
res = rLock.tryLock(waitTime, expireSeconds, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
if (res) {
|
||||
obj = joinPoint.proceed();
|
||||
} else {
|
||||
log.error("获取锁异常");
|
||||
}
|
||||
} finally {
|
||||
if (res) {
|
||||
rLock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
log.info("结束RedisLock环绕通知...");
|
||||
return obj;
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private RLock getLock(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) {
|
||||
String[] keys = distributedLock.lockKey();
|
||||
if (keys.length == 0) {
|
||||
throw new RuntimeException("keys不能为空");
|
||||
}
|
||||
String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(((MethodSignature) joinPoint.getSignature()).getMethod());
|
||||
Object[] args = joinPoint.getArgs();
|
||||
|
||||
LockModel lockModel = distributedLock.lockModel();
|
||||
if (!lockModel.equals(LockModel.MULTIPLE) && !lockModel.equals(LockModel.REDLOCK) && keys.length > 1) {
|
||||
throw new RuntimeException("参数有多个,锁模式为->" + lockModel.name() + ".无法锁定");
|
||||
}
|
||||
RLock rLock = null;
|
||||
String keyConstant = distributedLock.keyConstant();
|
||||
if (lockModel.equals(LockModel.AUTO)) {
|
||||
if (keys.length > 1) {
|
||||
lockModel = LockModel.REDLOCK;
|
||||
} else {
|
||||
lockModel = LockModel.REENTRANT;
|
||||
}
|
||||
}
|
||||
switch (lockModel) {
|
||||
case FAIR:
|
||||
rLock = redissonClient.getFairLock(getValueBySpEL(keys[0], parameterNames, args, keyConstant).get(0));
|
||||
break;
|
||||
case REDLOCK:
|
||||
List<RLock> rLocks = new ArrayList<>();
|
||||
for (String key : keys) {
|
||||
List<String> valueBySpEL = getValueBySpEL(key, parameterNames, args, keyConstant);
|
||||
for (String s : valueBySpEL) {
|
||||
rLocks.add(redissonClient.getLock(s));
|
||||
}
|
||||
}
|
||||
RLock[] locks = new RLock[rLocks.size()];
|
||||
int index = 0;
|
||||
for (RLock r : rLocks) {
|
||||
locks[index++] = r;
|
||||
}
|
||||
rLock = new RedissonRedLock(locks);
|
||||
break;
|
||||
case MULTIPLE:
|
||||
rLocks = new ArrayList<>();
|
||||
|
||||
for (String key : keys) {
|
||||
List<String> valueBySpEL = getValueBySpEL(key, parameterNames, args, keyConstant);
|
||||
for (String s : valueBySpEL) {
|
||||
rLocks.add(redissonClient.getLock(s));
|
||||
}
|
||||
}
|
||||
locks = new RLock[rLocks.size()];
|
||||
index = 0;
|
||||
for (RLock r : rLocks) {
|
||||
locks[index++] = r;
|
||||
}
|
||||
rLock = new RedissonMultiLock(locks);
|
||||
break;
|
||||
case REENTRANT:
|
||||
List<String> valueBySpEL = getValueBySpEL(keys[0], parameterNames, args, keyConstant);
|
||||
//如果spel表达式是数组或者LIST 则使用红锁
|
||||
if (valueBySpEL.size() == 1) {
|
||||
rLock = redissonClient.getLock(valueBySpEL.get(0));
|
||||
} else {
|
||||
locks = new RLock[valueBySpEL.size()];
|
||||
index = 0;
|
||||
for (String s : valueBySpEL) {
|
||||
locks[index++] = redissonClient.getLock(s);
|
||||
}
|
||||
rLock = new RedissonRedLock(locks);
|
||||
}
|
||||
break;
|
||||
case READ:
|
||||
rLock = redissonClient.getReadWriteLock(getValueBySpEL(keys[0], parameterNames, args, keyConstant).get(0)).readLock();
|
||||
break;
|
||||
case WRITE:
|
||||
rLock = redissonClient.getReadWriteLock(getValueBySpEL(keys[0], parameterNames, args, keyConstant).get(0)).writeLock();
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
return rLock;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过spring SpEL 获取参数
|
||||
*
|
||||
* @param key 定义的key值 以#开头 例如:#user
|
||||
* @param parameterNames 形参
|
||||
* @param values 形参值
|
||||
* @param keyConstant key的常亮
|
||||
* @return
|
||||
*/
|
||||
public List<String> getValueBySpEL(String key, String[] parameterNames, Object[] values, String keyConstant) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (!key.contains("#")) {
|
||||
String s = "redis:lock:" + key + keyConstant;
|
||||
log.info("lockKey:" + s);
|
||||
keys.add(s);
|
||||
return keys;
|
||||
}
|
||||
//spel解析器
|
||||
ExpressionParser parser = new SpelExpressionParser();
|
||||
//spel上下文
|
||||
EvaluationContext context = new StandardEvaluationContext();
|
||||
for (int i = 0; i < parameterNames.length; i++) {
|
||||
context.setVariable(parameterNames[i], values[i]);
|
||||
}
|
||||
Expression expression = parser.parseExpression(key);
|
||||
Object value = expression.getValue(context);
|
||||
if (value != null) {
|
||||
if (value instanceof List) {
|
||||
List value1 = (List) value;
|
||||
for (Object o : value1) {
|
||||
addKeys(keys, o, keyConstant);
|
||||
}
|
||||
} else if (value.getClass().isArray()) {
|
||||
Object[] obj = (Object[]) value;
|
||||
for (Object o : obj) {
|
||||
addKeys(keys, o, keyConstant);
|
||||
}
|
||||
} else {
|
||||
addKeys(keys, value, keyConstant);
|
||||
}
|
||||
}
|
||||
log.info("表达式key={},value={}", key, keys);
|
||||
return keys;
|
||||
}
|
||||
|
||||
private void addKeys(List<String> keys, Object o, String keyConstant) {
|
||||
keys.add("redis:lock:" + o.toString() + keyConstant);
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.jero.boot.starter.lock.client;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.redisson.api.RLock;
|
||||
import org.redisson.api.RedissonClient;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 分布式锁实现基于Redisson
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class RedissonLockClient {
|
||||
|
||||
@Autowired
|
||||
private RedissonClient redissonClient;
|
||||
|
||||
/**
|
||||
* 获取锁
|
||||
*/
|
||||
public RLock getLock(String lockKey) {
|
||||
return redissonClient.getLock(lockKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加锁操作
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean tryLock(String lockName, long expireSeconds) {
|
||||
return tryLock(lockName, 0, expireSeconds);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 加锁操作
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean tryLock(String lockName, long waitTime, long expireSeconds) {
|
||||
RLock rLock = getLock(lockName);
|
||||
boolean getLock = false;
|
||||
try {
|
||||
getLock = rLock.tryLock(waitTime, expireSeconds, TimeUnit.SECONDS);
|
||||
if (getLock) {
|
||||
log.info("获取锁成功,lockName={}", lockName);
|
||||
} else {
|
||||
log.info("获取锁失败,lockName={}", lockName);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
log.error("获取式锁异常,lockName=" + lockName, e);
|
||||
getLock = false;
|
||||
}
|
||||
return getLock;
|
||||
}
|
||||
|
||||
/**
|
||||
* 锁lockKey
|
||||
*
|
||||
* @param lockKey
|
||||
* @return
|
||||
*/
|
||||
public RLock lock(String lockKey) {
|
||||
RLock lock = getLock(lockKey);
|
||||
lock.lock();
|
||||
return lock;
|
||||
}
|
||||
|
||||
/**
|
||||
* 锁lockKey
|
||||
*
|
||||
* @param lockKey
|
||||
* @param leaseTime
|
||||
* @return
|
||||
*/
|
||||
public RLock lock(String lockKey, long leaseTime) {
|
||||
RLock lock = getLock(lockKey);
|
||||
lock.lock(leaseTime, TimeUnit.SECONDS);
|
||||
return lock;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 解锁
|
||||
*
|
||||
* @param lockName 锁名称
|
||||
*/
|
||||
public void unlock(String lockName) {
|
||||
redissonClient.getLock(lockName).unlock();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.jero.boot.starter.lock.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.boot.starter.lock.core.RedissonManager;
|
||||
import com.jero.boot.starter.lock.prop.RedissonProperties;
|
||||
import org.redisson.api.RedissonClient;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
|
||||
/**
|
||||
* Redisson自动化配置
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@ConditionalOnClass(RedissonProperties.class)
|
||||
@EnableConfigurationProperties(RedissonProperties.class)
|
||||
public class RedissonConfiguration {
|
||||
|
||||
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(RedissonClient.class)
|
||||
public RedissonClient redissonClient(RedissonProperties redissonProperties) {
|
||||
RedissonManager redissonManager = new RedissonManager(redissonProperties);
|
||||
log.info("RedissonManager初始化完成,当前连接方式:" + redissonProperties.getType() + ",连接地址:" + redissonProperties.getAddress());
|
||||
return redissonManager.getRedisson();
|
||||
}
|
||||
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.jero.boot.starter.lock.core;
|
||||
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.boot.starter.lock.core.strategy.RedissonConfigStrategy;
|
||||
import com.jero.boot.starter.lock.prop.RedissonProperties;
|
||||
import com.jero.boot.starter.lock.core.strategy.impl.ClusterRedissonConfigStrategyImpl;
|
||||
import com.jero.boot.starter.lock.core.strategy.impl.MasterslaveRedissonConfigStrategyImpl;
|
||||
import com.jero.boot.starter.lock.core.strategy.impl.SentinelRedissonConfigStrategyImpl;
|
||||
import com.jero.boot.starter.lock.core.strategy.impl.StandaloneRedissonConfigStrategyImpl;
|
||||
import com.jero.boot.starter.lock.enums.RedisConnectionType;
|
||||
import org.redisson.Redisson;
|
||||
import org.redisson.config.Config;
|
||||
|
||||
|
||||
/**
|
||||
* Redisson配置管理器,用于初始化的redisson实例
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-12
|
||||
*/
|
||||
@Slf4j
|
||||
public class RedissonManager {
|
||||
|
||||
private Config config = new Config();
|
||||
|
||||
private Redisson redisson = null;
|
||||
|
||||
public RedissonManager() {
|
||||
}
|
||||
|
||||
public RedissonManager(RedissonProperties redissonProperties) {
|
||||
//装配开关
|
||||
Boolean enabled = redissonProperties.getEnabled();
|
||||
if (enabled) {
|
||||
try {
|
||||
config = RedissonConfigFactory.getInstance().createConfig(redissonProperties);
|
||||
redisson = (Redisson) Redisson.create(config);
|
||||
} catch (Exception e) {
|
||||
log.error("Redisson初始化错误", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Redisson getRedisson() {
|
||||
return redisson;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redisson连接方式配置工厂
|
||||
* 双重检查锁
|
||||
*/
|
||||
static class RedissonConfigFactory {
|
||||
|
||||
private RedissonConfigFactory() {
|
||||
}
|
||||
|
||||
private static volatile RedissonConfigFactory factory = null;
|
||||
|
||||
public static RedissonConfigFactory getInstance() {
|
||||
if (factory == null) {
|
||||
synchronized (Object.class) {
|
||||
if (factory == null) {
|
||||
factory = new RedissonConfigFactory();
|
||||
}
|
||||
}
|
||||
}
|
||||
return factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据连接类型創建连接方式的配置
|
||||
*
|
||||
* @param redissonProperties
|
||||
* @return Config
|
||||
*/
|
||||
Config createConfig(RedissonProperties redissonProperties) {
|
||||
Preconditions.checkNotNull(redissonProperties);
|
||||
Preconditions.checkNotNull(redissonProperties.getAddress(), "redis地址未配置");
|
||||
RedisConnectionType connectionType = redissonProperties.getType();
|
||||
// 声明连接方式
|
||||
RedissonConfigStrategy redissonConfigStrategy;
|
||||
if (connectionType.equals(RedisConnectionType.SENTINEL)) {
|
||||
redissonConfigStrategy = new SentinelRedissonConfigStrategyImpl();
|
||||
} else if (connectionType.equals(RedisConnectionType.CLUSTER)) {
|
||||
redissonConfigStrategy = new ClusterRedissonConfigStrategyImpl();
|
||||
} else if (connectionType.equals(RedisConnectionType.MASTERSLAVE)) {
|
||||
redissonConfigStrategy = new MasterslaveRedissonConfigStrategyImpl();
|
||||
} else {
|
||||
redissonConfigStrategy = new StandaloneRedissonConfigStrategyImpl();
|
||||
}
|
||||
Preconditions.checkNotNull(redissonConfigStrategy, "连接方式创建异常");
|
||||
|
||||
return redissonConfigStrategy.createRedissonConfig(redissonProperties);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.jero.boot.starter.lock.core.strategy;
|
||||
|
||||
import com.jero.boot.starter.lock.prop.RedissonProperties;
|
||||
import org.redisson.config.Config;
|
||||
|
||||
/**
|
||||
* Redisson配置构建接口
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
public interface RedissonConfigStrategy {
|
||||
|
||||
/**
|
||||
* 根据不同的Redis配置策略创建对应的Config
|
||||
*
|
||||
* @param redissonProperties
|
||||
* @return Config
|
||||
*/
|
||||
Config createRedissonConfig(RedissonProperties redissonProperties);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.jero.boot.starter.lock.core.strategy.impl;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import com.jero.boot.starter.lock.core.strategy.RedissonConfigStrategy;
|
||||
import com.jero.boot.starter.lock.prop.RedissonProperties;
|
||||
import com.jero.boot.starter.lock.enums.GlobalConstant;
|
||||
import org.redisson.config.Config;
|
||||
|
||||
|
||||
/**
|
||||
* 集群方式Redisson配置
|
||||
* cluster方式至少6个节点(3主3从)
|
||||
* 配置方式:127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Slf4j
|
||||
public class ClusterRedissonConfigStrategyImpl implements RedissonConfigStrategy {
|
||||
|
||||
@Override
|
||||
public Config createRedissonConfig(RedissonProperties redissonProperties) {
|
||||
Config config = new Config();
|
||||
try {
|
||||
String address = redissonProperties.getAddress();
|
||||
String password = redissonProperties.getPassword();
|
||||
String[] addrTokens = address.split(",");
|
||||
// 设置集群(cluster)节点的服务IP和端口
|
||||
for (int i = 0; i < addrTokens.length; i++) {
|
||||
config.useClusterServers().addNodeAddress(GlobalConstant.REDIS_CONNECTION_PREFIX + addrTokens[i]);
|
||||
if (StringUtils.isNotBlank(password)) {
|
||||
config.useClusterServers().setPassword(password);
|
||||
}
|
||||
}
|
||||
log.info("初始化集群方式Config,连接地址:" + address);
|
||||
} catch (Exception e) {
|
||||
log.error("集群Redisson初始化错误", e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.jero.boot.starter.lock.core.strategy.impl;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import com.jero.boot.starter.lock.core.strategy.RedissonConfigStrategy;
|
||||
import com.jero.boot.starter.lock.prop.RedissonProperties;
|
||||
import com.jero.boot.starter.lock.enums.GlobalConstant;
|
||||
import org.redisson.config.Config;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 主从方式Redisson配置
|
||||
* <p>配置方式: 127.0.0.1:6379(主),127.0.0.1:6380(子),127.0.0.1:6381(子)</p>
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Slf4j
|
||||
public class MasterslaveRedissonConfigStrategyImpl implements RedissonConfigStrategy {
|
||||
|
||||
@Override
|
||||
public Config createRedissonConfig(RedissonProperties redissonProperties) {
|
||||
Config config = new Config();
|
||||
try {
|
||||
String address = redissonProperties.getAddress();
|
||||
String password = redissonProperties.getPassword();
|
||||
int database = redissonProperties.getDatabase();
|
||||
String[] addrTokens = address.split(",");
|
||||
String masterNodeAddr = addrTokens[0];
|
||||
// 设置主节点ip
|
||||
config.useMasterSlaveServers().setMasterAddress(masterNodeAddr);
|
||||
if (StringUtils.isNotBlank(password)) {
|
||||
config.useMasterSlaveServers().setPassword(password);
|
||||
}
|
||||
config.useMasterSlaveServers().setDatabase(database);
|
||||
// 设置从节点,移除第一个节点,默认第一个为主节点
|
||||
List<String> slaveList = new ArrayList<>();
|
||||
for (String addrToken : addrTokens) {
|
||||
slaveList.add(GlobalConstant.REDIS_CONNECTION_PREFIX + addrToken);
|
||||
}
|
||||
slaveList.remove(0);
|
||||
|
||||
config.useMasterSlaveServers().addSlaveAddress((String[]) slaveList.toArray());
|
||||
log.info("初始化主从方式Config,redisAddress:" + address);
|
||||
} catch (Exception e) {
|
||||
log.error("主从Redisson初始化错误", e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.jero.boot.starter.lock.core.strategy.impl;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import com.jero.boot.starter.lock.core.strategy.RedissonConfigStrategy;
|
||||
import com.jero.boot.starter.lock.prop.RedissonProperties;
|
||||
import com.jero.boot.starter.lock.enums.GlobalConstant;
|
||||
import org.redisson.config.Config;
|
||||
|
||||
|
||||
/**
|
||||
* 哨兵方式Redis连接配置
|
||||
* 比如sentinel.conf里配置为sentinel monitor my-sentinel-name 127.0.0.1 6379 2,那么这里就配置my-sentinel-name
|
||||
* 配置方式:my-sentinel-name,127.0.0.1:26379,127.0.0.1:26389,127.0.0.1:26399
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Slf4j
|
||||
public class SentinelRedissonConfigStrategyImpl implements RedissonConfigStrategy {
|
||||
|
||||
@Override
|
||||
public Config createRedissonConfig(RedissonProperties redissonProperties) {
|
||||
Config config = new Config();
|
||||
try {
|
||||
String address = redissonProperties.getAddress();
|
||||
String password = redissonProperties.getPassword();
|
||||
int database = redissonProperties.getDatabase();
|
||||
String[] addrTokens = address.split(",");
|
||||
String sentinelAliasName = addrTokens[0];
|
||||
// 设置redis配置文件sentinel.conf配置的sentinel别名
|
||||
config.useSentinelServers().setMasterName(sentinelAliasName);
|
||||
config.useSentinelServers().setDatabase(database);
|
||||
if (StringUtils.isNotBlank(password)) {
|
||||
config.useSentinelServers().setPassword(password);
|
||||
}
|
||||
// 设置哨兵节点的服务IP和端口
|
||||
for (int i = 1; i < addrTokens.length; i++) {
|
||||
config.useSentinelServers().addSentinelAddress(GlobalConstant.REDIS_CONNECTION_PREFIX+ addrTokens[i]);
|
||||
}
|
||||
log.info("初始化哨兵方式Config,redisAddress:" + address);
|
||||
} catch (Exception e) {
|
||||
log.error("哨兵Redisson初始化错误", e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.jero.boot.starter.lock.core.strategy.impl;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import com.jero.boot.starter.lock.core.strategy.RedissonConfigStrategy;
|
||||
import com.jero.boot.starter.lock.prop.RedissonProperties;
|
||||
import com.jero.boot.starter.lock.enums.GlobalConstant;
|
||||
import org.redisson.config.Config;
|
||||
|
||||
|
||||
/**
|
||||
* 单机方式Redisson配置
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Slf4j
|
||||
public class StandaloneRedissonConfigStrategyImpl implements RedissonConfigStrategy {
|
||||
|
||||
@Override
|
||||
public Config createRedissonConfig(RedissonProperties redissonProperties) {
|
||||
Config config = new Config();
|
||||
try {
|
||||
String address = redissonProperties.getAddress();
|
||||
String password = redissonProperties.getPassword();
|
||||
int database = redissonProperties.getDatabase();
|
||||
String redisAddr = GlobalConstant.REDIS_CONNECTION_PREFIX + address;
|
||||
config.useSingleServer().setAddress(redisAddr);
|
||||
config.useSingleServer().setDatabase(database);
|
||||
if (StringUtils.isNotBlank(password)) {
|
||||
config.useSingleServer().setPassword(password);
|
||||
}
|
||||
log.info("初始化Redisson单机配置,连接地址:" + address);
|
||||
} catch (Exception e) {
|
||||
log.error("单机Redisson初始化错误", e);
|
||||
e.printStackTrace();
|
||||
}
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.jero.boot.starter.lock.enums;
|
||||
|
||||
/**
|
||||
* 全局常量枚举
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
|
||||
public interface GlobalConstant {
|
||||
|
||||
/**
|
||||
* Redis地址连接前缀
|
||||
*/
|
||||
String REDIS_CONNECTION_PREFIX = "redis://";
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.jero.boot.starter.lock.enums;
|
||||
|
||||
/**
|
||||
* 锁的模式
|
||||
* @author jeecg
|
||||
*/
|
||||
public enum LockModel {
|
||||
//可重入锁
|
||||
REENTRANT,
|
||||
//公平锁
|
||||
FAIR,
|
||||
//联锁(可以把一组锁当作一个锁来加锁和释放)
|
||||
MULTIPLE,
|
||||
//红锁
|
||||
REDLOCK,
|
||||
//读锁
|
||||
READ,
|
||||
//写锁
|
||||
WRITE,
|
||||
//自动模式,当参数只有一个.使用 REENTRANT 参数多个 REDLOCK
|
||||
AUTO
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.jero.boot.starter.lock.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* Redis连接方式
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum RedisConnectionType {
|
||||
/**
|
||||
* 单机部署方式(默认)
|
||||
*/
|
||||
STANDALONE("standalone", "单机部署方式"),
|
||||
/**
|
||||
* 哨兵部署方式
|
||||
*/
|
||||
SENTINEL("sentinel", "哨兵部署方式"),
|
||||
/**
|
||||
* 集群部署方式
|
||||
*/
|
||||
CLUSTER("cluster", "集群方式"),
|
||||
/**
|
||||
* 主从部署方式
|
||||
*/
|
||||
MASTERSLAVE("masterslave", "主从部署方式");
|
||||
|
||||
/**
|
||||
* 编码
|
||||
*/
|
||||
private final String code;
|
||||
/**
|
||||
* 名称
|
||||
*/
|
||||
private final String name;
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.jero.boot.starter.lock.prop;
|
||||
|
||||
import lombok.Data;
|
||||
import com.jero.boot.starter.lock.enums.RedisConnectionType;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* Redisson配置映射类
|
||||
*
|
||||
* @author zyf
|
||||
* @date 2020-11-11
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "jeecg.redisson")
|
||||
public class RedissonProperties {
|
||||
|
||||
/**
|
||||
* redis主机地址,ip:port,多个用逗号(,)分隔
|
||||
*/
|
||||
private String address;
|
||||
/**
|
||||
* 连接类型
|
||||
*/
|
||||
private RedisConnectionType type;
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
private String password;
|
||||
/**
|
||||
* 数据库(默认0)
|
||||
*/
|
||||
private int database;
|
||||
|
||||
/**
|
||||
* 是否装配redisson配置
|
||||
*/
|
||||
private Boolean enabled = true;
|
||||
|
||||
}
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
package com.jero.boot.starter.rabbitmq.client;
|
||||
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.boot.starter.rabbitmq.event.EventObj;
|
||||
import com.jero.boot.starter.rabbitmq.event.JeroRemoteApplicationEvent;
|
||||
import com.jero.boot.starter.rabbitmq.exchange.DelayExchangeBuilder;
|
||||
import com.jero.common.annotation.RabbitComponent;
|
||||
import com.jero.common.base.BaseMap;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.amqp.core.*;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitAdmin;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cloud.bus.BusProperties;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.lang.reflect.Method;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 消息队列客户端
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class RabbitMqClient {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(RabbitMqClient.class);
|
||||
|
||||
private final RabbitAdmin rabbitAdmin;
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
|
||||
@Resource
|
||||
private SimpleMessageListenerContainer messageListenerContainer;
|
||||
|
||||
@Resource
|
||||
BusProperties busProperties;
|
||||
@Resource
|
||||
private ApplicationEventPublisher publisher;
|
||||
|
||||
|
||||
@Resource
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
|
||||
@Bean
|
||||
public void initQueue() {
|
||||
Map<String, Object> beansWithRqbbitComponentMap = this.applicationContext.getBeansWithAnnotation(RabbitComponent.class);
|
||||
Class<? extends Object> clazz = null;
|
||||
for (Map.Entry<String, Object> entry : beansWithRqbbitComponentMap.entrySet()) {
|
||||
log.info("初始化队列............");
|
||||
//获取到实例对象的class信息
|
||||
clazz = entry.getValue().getClass();
|
||||
Method[] methods = clazz.getMethods();
|
||||
RabbitListener rabbitListener = clazz.getAnnotation(RabbitListener.class);
|
||||
if (ObjectUtil.isNotEmpty(rabbitListener)) {
|
||||
createQueue(rabbitListener);
|
||||
}
|
||||
for (Method method : methods) {
|
||||
RabbitListener methodRabbitListener = method.getAnnotation(RabbitListener.class);
|
||||
if (ObjectUtil.isNotEmpty(methodRabbitListener)) {
|
||||
createQueue(methodRabbitListener);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化队列
|
||||
*
|
||||
* @param rabbitListener
|
||||
*/
|
||||
private void createQueue(RabbitListener rabbitListener) {
|
||||
String[] queues = rabbitListener.queues();
|
||||
DirectExchange directExchange = createExchange(DelayExchangeBuilder.DELAY_EXCHANGE);
|
||||
//创建交换机
|
||||
rabbitAdmin.declareExchange(directExchange);
|
||||
if (ObjectUtil.isNotEmpty(queues)) {
|
||||
for (String queueName : queues) {
|
||||
Queue queue = new Queue(queueName);
|
||||
addQueue(queue);
|
||||
Binding binding = BindingBuilder.bind(queue).to(directExchange).with(queueName);
|
||||
rabbitAdmin.declareBinding(binding);
|
||||
log.info("队列创建成功:" + queueName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private Map sentObj = new HashMap<>();
|
||||
|
||||
|
||||
@Autowired
|
||||
public RabbitMqClient(RabbitAdmin rabbitAdmin, RabbitTemplate rabbitTemplate) {
|
||||
this.rabbitAdmin = rabbitAdmin;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送远程事件
|
||||
*
|
||||
* @param handlerName
|
||||
* @param baseMap
|
||||
*/
|
||||
public void publishEvent(String handlerName, BaseMap baseMap) {
|
||||
EventObj eventObj = new EventObj();
|
||||
eventObj.setHandlerName(handlerName);
|
||||
eventObj.setBaseMap(baseMap);
|
||||
publisher.publishEvent(new JeroRemoteApplicationEvent(eventObj, busProperties.getId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换Message对象
|
||||
*
|
||||
* @param messageType 返回消息类型 MessageProperties类中常量
|
||||
* @param msg
|
||||
* @return
|
||||
*/
|
||||
public Message getMessage(String messageType, Object msg) {
|
||||
MessageProperties messageProperties = new MessageProperties();
|
||||
messageProperties.setContentType(messageType);
|
||||
Message message = new Message(msg.toString().getBytes(), messageProperties);
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 有绑定Key的Exchange发送
|
||||
*
|
||||
* @param routingKey
|
||||
* @param msg
|
||||
*/
|
||||
public void sendMessageToExchange(TopicExchange topicExchange, String routingKey, Object msg) {
|
||||
Message message = getMessage(MessageProperties.CONTENT_TYPE_JSON, msg);
|
||||
rabbitTemplate.send(topicExchange.getName(), routingKey, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 没有绑定KEY的Exchange发送
|
||||
*
|
||||
* @param exchange
|
||||
* @param msg
|
||||
*/
|
||||
public void sendMessageToExchange(TopicExchange topicExchange, AbstractExchange exchange, String msg) {
|
||||
addExchange(exchange);
|
||||
logger.info("RabbitMQ send " + exchange.getName() + "->" + msg);
|
||||
rabbitTemplate.convertAndSend(topicExchange.getName(), msg);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*
|
||||
* @param queueName 队列名称
|
||||
* @param params 消息内容map
|
||||
*/
|
||||
public void sendMessage(String queueName, Object params) {
|
||||
log.info("发送消息到mq");
|
||||
try {
|
||||
rabbitTemplate.convertAndSend(DelayExchangeBuilder.DELAY_EXCHANGE, queueName, params, message -> {
|
||||
return message;
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*
|
||||
* @param queueName 队列名称
|
||||
*/
|
||||
public void sendMessage(String queueName) {
|
||||
this.send(queueName, this.sentObj, 0);
|
||||
this.sentObj.clear();
|
||||
}
|
||||
|
||||
|
||||
public RabbitMqClient put(String key, Object value) {
|
||||
this.sentObj.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟发送消息
|
||||
*
|
||||
* @param queueName 队列名称
|
||||
* @param params 消息内容params
|
||||
* @param expiration 延迟时间 单位毫秒
|
||||
*/
|
||||
public void sendMessage(String queueName, Object params, Integer expiration) {
|
||||
this.send(queueName, params, expiration);
|
||||
}
|
||||
|
||||
private void send(String queueName, Object params, Integer expiration) {
|
||||
Queue queue = new Queue(queueName);
|
||||
addQueue(queue);
|
||||
CustomExchange customExchange = DelayExchangeBuilder.buildExchange();
|
||||
rabbitAdmin.declareExchange(customExchange);
|
||||
Binding binding = BindingBuilder.bind(queue).to(customExchange).with(queueName).noargs();
|
||||
rabbitAdmin.declareBinding(binding);
|
||||
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
log.debug("发送时间:" + sf.format(new Date()));
|
||||
messageListenerContainer.setQueueNames(queueName);
|
||||
/* messageListenerContainer.setMessageListener(new MqListener<Message>() {
|
||||
@Override
|
||||
public void onMessage(Message message, Channel channel) {
|
||||
MqListener messageListener = SpringContextHolder.getHandler(queueName + "Listener", MqListener.class);
|
||||
if (ObjectUtil.isNotEmpty(messageListener)) {
|
||||
messageListener.onMessage(message, channel);
|
||||
}
|
||||
}
|
||||
});*/
|
||||
rabbitTemplate.convertAndSend(DelayExchangeBuilder.DEFAULT_DELAY_EXCHANGE, queueName, params, message -> {
|
||||
if (expiration != null && expiration > 0) {
|
||||
message.getMessageProperties().setHeader("x-delay", expiration);
|
||||
}
|
||||
return message;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 给queue发送消息
|
||||
*
|
||||
* @param queueName
|
||||
*/
|
||||
public String receiveFromQueue(String queueName) {
|
||||
return receiveFromQueue(DirectExchange.DEFAULT, queueName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 给direct交换机指定queue发送消息
|
||||
*
|
||||
* @param directExchange
|
||||
* @param queueName
|
||||
*/
|
||||
public String receiveFromQueue(DirectExchange directExchange, String queueName) {
|
||||
Queue queue = new Queue(queueName);
|
||||
addQueue(queue);
|
||||
Binding binding = BindingBuilder.bind(queue).to(directExchange).withQueueName();
|
||||
rabbitAdmin.declareBinding(binding);
|
||||
String messages = (String) rabbitTemplate.receiveAndConvert(queueName);
|
||||
System.out.println("Receive:" + messages);
|
||||
return messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建Exchange
|
||||
*
|
||||
* @param exchange
|
||||
*/
|
||||
public void addExchange(AbstractExchange exchange) {
|
||||
rabbitAdmin.declareExchange(exchange);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除一个Exchange
|
||||
*
|
||||
* @param exchangeName
|
||||
*/
|
||||
public boolean deleteExchange(String exchangeName) {
|
||||
return rabbitAdmin.deleteExchange(exchangeName);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 声明其名称自动命名的队列。它是用exclusive=true、autoDelete=true和 durable = false
|
||||
*
|
||||
* @return Queue
|
||||
*/
|
||||
public Queue addQueue() {
|
||||
return rabbitAdmin.declareQueue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个指定的Queue
|
||||
*
|
||||
* @param queue
|
||||
* @return queueName
|
||||
*/
|
||||
public String addQueue(Queue queue) {
|
||||
return rabbitAdmin.declareQueue(queue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除一个队列
|
||||
*
|
||||
* @param queueName the name of the queue.
|
||||
* @param unused true if the queue should be deleted only if not in use.
|
||||
* @param empty true if the queue should be deleted only if empty.
|
||||
*/
|
||||
public void deleteQueue(String queueName, boolean unused, boolean empty) {
|
||||
rabbitAdmin.deleteQueue(queueName, unused, empty);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除一个队列
|
||||
*
|
||||
* @param queueName
|
||||
* @return true if the queue existed and was deleted.
|
||||
*/
|
||||
public boolean deleteQueue(String queueName) {
|
||||
return rabbitAdmin.deleteQueue(queueName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定一个队列到一个匹配型交换器使用一个routingKey
|
||||
*
|
||||
* @param queue
|
||||
* @param exchange
|
||||
* @param routingKey
|
||||
*/
|
||||
public void addBinding(Queue queue, TopicExchange exchange, String routingKey) {
|
||||
Binding binding = BindingBuilder.bind(queue).to(exchange).with(routingKey);
|
||||
rabbitAdmin.declareBinding(binding);
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定一个Exchange到一个匹配型Exchange 使用一个routingKey
|
||||
*
|
||||
* @param exchange
|
||||
* @param topicExchange
|
||||
* @param routingKey
|
||||
*/
|
||||
public void addBinding(Exchange exchange, TopicExchange topicExchange, String routingKey) {
|
||||
Binding binding = BindingBuilder.bind(exchange).to(topicExchange).with(routingKey);
|
||||
rabbitAdmin.declareBinding(binding);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去掉一个binding
|
||||
*
|
||||
* @param binding
|
||||
*/
|
||||
public void removeBinding(Binding binding) {
|
||||
rabbitAdmin.removeBinding(binding);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建交换器
|
||||
*
|
||||
* @param exchangeName
|
||||
* @return
|
||||
*/
|
||||
public DirectExchange createExchange(String exchangeName) {
|
||||
return new DirectExchange(exchangeName, true, false);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.jero.boot.starter.rabbitmq.config;
|
||||
|
||||
|
||||
import com.jero.boot.starter.rabbitmq.event.JeroRemoteApplicationEvent;
|
||||
import org.springframework.amqp.core.AcknowledgeMode;
|
||||
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
|
||||
import org.springframework.amqp.rabbit.core.RabbitAdmin;
|
||||
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
|
||||
import org.springframework.amqp.support.ConsumerTagStrategy;
|
||||
import org.springframework.cloud.bus.jackson.RemoteApplicationEventScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 消息队列配置类
|
||||
*
|
||||
* @author zyf
|
||||
*/
|
||||
@Configuration
|
||||
@RemoteApplicationEventScan(basePackageClasses = JeroRemoteApplicationEvent.class)
|
||||
public class RabbitMqConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
|
||||
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
|
||||
//设置忽略声明异常
|
||||
rabbitAdmin.setIgnoreDeclarationExceptions(true);
|
||||
return rabbitAdmin;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Bean
|
||||
public SimpleMessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory) {
|
||||
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
|
||||
container.setConnectionFactory(connectionFactory);
|
||||
//手动确认
|
||||
container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
|
||||
//当前的消费者数量
|
||||
container.setConcurrentConsumers(1);
|
||||
//最大的消费者数量
|
||||
container.setMaxConcurrentConsumers(1);
|
||||
//是否重回队列
|
||||
container.setDefaultRequeueRejected(true);
|
||||
|
||||
//消费端的标签策略
|
||||
container.setConsumerTagStrategy(new ConsumerTagStrategy() {
|
||||
@Override
|
||||
public String createConsumerTag(String queue) {
|
||||
return queue + "_" + UUID.randomUUID().toString();
|
||||
}
|
||||
});
|
||||
return container;
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.jero.boot.starter.rabbitmq.core;
|
||||
|
||||
import com.rabbitmq.client.Channel;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.boot.starter.rabbitmq.listenter.MqListener;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Slf4j
|
||||
public class BaseRabbiMqHandler<T> {
|
||||
|
||||
public void onMessage(T t, Long deliveryTag, Channel channel, MqListener mqListener) {
|
||||
try {
|
||||
mqListener.handler(t, channel);
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception e) {
|
||||
log.info("接收消息失败,重新放回队列");
|
||||
try {
|
||||
/**
|
||||
* deliveryTag:该消息的index
|
||||
* multiple:是否批量.true:将一次性拒绝所有小于deliveryTag的消息。
|
||||
* requeue:被拒绝的是否重新入队列
|
||||
*/
|
||||
channel.basicNack(deliveryTag, false, true);
|
||||
} catch (IOException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.jero.boot.starter.rabbitmq.core;
|
||||
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.core.MessageProperties;
|
||||
import org.springframework.amqp.support.converter.MessageConversionException;
|
||||
import org.springframework.amqp.support.converter.MessageConverter;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class MapMessageConverter implements MessageConverter {
|
||||
@Override
|
||||
public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
|
||||
return new Message(object.toString().getBytes(), messageProperties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object fromMessage(Message message) throws MessageConversionException {
|
||||
String contentType = message.getMessageProperties().getContentType();
|
||||
if (null != contentType && contentType.contains("text")) {
|
||||
return new String(message.getBody());
|
||||
} else {
|
||||
ObjectInputStream objInt = null;
|
||||
try {
|
||||
ByteArrayInputStream byteInt = new ByteArrayInputStream(message.getBody());
|
||||
objInt = new ObjectInputStream(byteInt);
|
||||
//byte[]转map
|
||||
Map map = (HashMap) objInt.readObject();
|
||||
return map;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.jero.boot.starter.rabbitmq.event;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
|
||||
import com.jero.common.util.SpringContextHolder;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 监听远程事件,并分发消息到业务模块消息处理器
|
||||
*/
|
||||
@Component
|
||||
public class BaseApplicationEvent implements ApplicationListener<JeroRemoteApplicationEvent> {
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(JeroRemoteApplicationEvent jeroRemoteApplicationEvent) {
|
||||
EventObj eventObj = jeroRemoteApplicationEvent.getEventObj();
|
||||
if (ObjectUtil.isNotEmpty(eventObj)) {
|
||||
//获取业务模块消息处理器
|
||||
JeroBusEventHandler busEventHandler = SpringContextHolder.getHandler(eventObj.getHandlerName(), JeroBusEventHandler.class);
|
||||
if (ObjectUtil.isNotEmpty(busEventHandler)) {
|
||||
//通知业务模块
|
||||
busEventHandler.onMessage(eventObj);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.jero.boot.starter.rabbitmq.event;
|
||||
|
||||
import lombok.Data;
|
||||
import com.jero.common.base.BaseMap;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 远程事件数据对象
|
||||
*/
|
||||
@Data
|
||||
public class EventObj implements Serializable {
|
||||
/**
|
||||
* 数据对象
|
||||
*/
|
||||
private BaseMap baseMap;
|
||||
/**
|
||||
* 自定义业务模块消息处理器beanName
|
||||
*/
|
||||
private String handlerName;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.jero.boot.starter.rabbitmq.event;
|
||||
|
||||
/**
|
||||
* 业务模块消息处理器接口
|
||||
*/
|
||||
public interface JeroBusEventHandler {
|
||||
void onMessage(EventObj map);
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.jero.boot.starter.rabbitmq.event;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.cloud.bus.event.RemoteApplicationEvent;
|
||||
|
||||
/**
|
||||
* 自定义网关刷新远程事件
|
||||
*
|
||||
* @author : zyf
|
||||
* @date :2020-11-10
|
||||
*/
|
||||
@Data
|
||||
public class JeroRemoteApplicationEvent extends RemoteApplicationEvent {
|
||||
|
||||
private JeroRemoteApplicationEvent() {
|
||||
}
|
||||
|
||||
private EventObj eventObj;
|
||||
|
||||
public JeroRemoteApplicationEvent(EventObj source, String originService, String destinationService) {
|
||||
super(source, originService, destinationService);
|
||||
this.eventObj = source;
|
||||
}
|
||||
|
||||
public JeroRemoteApplicationEvent(EventObj source, String originService) {
|
||||
super(source, originService, null);
|
||||
this.eventObj = source;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.jero.boot.starter.rabbitmq.exchange;
|
||||
|
||||
import org.springframework.amqp.core.CustomExchange;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 延迟交换器构造器
|
||||
* @author: zyf
|
||||
* @date: 2019/3/8 13:31
|
||||
* @description:
|
||||
*/
|
||||
public class DelayExchangeBuilder {
|
||||
/**
|
||||
* 默认延迟消息交换器
|
||||
*/
|
||||
public final static String DEFAULT_DELAY_EXCHANGE = "jeecg.delayed.exchange";
|
||||
/**
|
||||
* 普通交换器
|
||||
*/
|
||||
public final static String DELAY_EXCHANGE = "jeecg.direct.exchange";
|
||||
|
||||
/**
|
||||
* 构建延迟消息交换器
|
||||
* @return
|
||||
*/
|
||||
public static CustomExchange buildExchange() {
|
||||
Map<String, Object> args = new HashMap<String, Object>();
|
||||
args.put("x-delayed-type", "direct");
|
||||
return new CustomExchange(DEFAULT_DELAY_EXCHANGE, "x-delayed-message", true, false, args);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.jero.boot.starter.rabbitmq.listenter;
|
||||
|
||||
import com.rabbitmq.client.Channel;
|
||||
|
||||
public interface MqListener<T> {
|
||||
|
||||
default void handler(T map, Channel channel) {
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.jero.boot.starter.redis.client;
|
||||
|
||||
import com.jero.common.base.BaseMap;
|
||||
import com.jero.common.constant.GlobalConstants;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* redis客户端
|
||||
*/
|
||||
@Configuration
|
||||
public class JeroRedisClient {
|
||||
|
||||
@Resource(name = "starterRedisTemplate")
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*
|
||||
* @param handlerName
|
||||
* @param params
|
||||
*/
|
||||
public void sendMessage(String handlerName, BaseMap params) {
|
||||
params.put(GlobalConstants.HANDLER_NAME, handlerName);
|
||||
redisTemplate.convertAndSend(GlobalConstants.REDIS_TOPIC_NAME, params);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据key查询缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public <T> T get(String key) {
|
||||
return key == null ? null : (T) redisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.jero.boot.starter.redis.config;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.jero.boot.starter.redis.prop.JeroRedisProperties;
|
||||
import com.jero.boot.starter.redis.service.RedisReceiver;
|
||||
import com.jero.common.constant.GlobalConstants;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.listener.ChannelTopic;
|
||||
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
|
||||
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
/**
|
||||
* redis配置
|
||||
*
|
||||
* @author jeecg
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(JeroRedisProperties.class)
|
||||
@ConditionalOnProperty(value = "spring.redis.enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class RedisConfiguration {
|
||||
|
||||
|
||||
/**
|
||||
* RedisTemplate配置
|
||||
*
|
||||
* @param lettuceConnectionFactory
|
||||
* @return
|
||||
*/
|
||||
@Bean("starterRedisTemplate")
|
||||
public RedisTemplate<String, Object> starterRedisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
|
||||
log.info(" --- redis config init --- ");
|
||||
// 设置序列化
|
||||
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
|
||||
ObjectMapper om = new ObjectMapper();
|
||||
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
|
||||
jackson2JsonRedisSerializer.setObjectMapper(om);
|
||||
// 配置redisTemplate
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
|
||||
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
|
||||
RedisSerializer<?> stringSerializer = new StringRedisSerializer();
|
||||
redisTemplate.setKeySerializer(stringSerializer);// key序列化
|
||||
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化
|
||||
redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化
|
||||
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化
|
||||
redisTemplate.afterPropertiesSet();
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* redis 监听配置
|
||||
*
|
||||
* @param redisConnectionFactory redis 配置
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory, RedisReceiver redisReceiver, MessageListenerAdapter commonListenerAdapter) {
|
||||
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
|
||||
container.setConnectionFactory(redisConnectionFactory);
|
||||
container.addMessageListener(commonListenerAdapter, new ChannelTopic(GlobalConstants.REDIS_TOPIC_NAME));
|
||||
return container;
|
||||
}
|
||||
|
||||
@Bean
|
||||
MessageListenerAdapter commonListenerAdapter(RedisReceiver redisReceiver) {
|
||||
MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(redisReceiver, "onMessage");
|
||||
messageListenerAdapter.setSerializer(jacksonSerializer());
|
||||
return messageListenerAdapter;
|
||||
}
|
||||
|
||||
private Jackson2JsonRedisSerializer jacksonSerializer() {
|
||||
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
|
||||
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
|
||||
return jackson2JsonRedisSerializer;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.jero.boot.starter.redis.listener;
|
||||
|
||||
import com.jero.common.base.BaseMap;
|
||||
|
||||
/**
|
||||
* 自定义消息监听
|
||||
*/
|
||||
public interface JeroRedisListerer {
|
||||
|
||||
void onMessage(BaseMap message);
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.jero.boot.starter.redis.prop;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* redis配置
|
||||
*
|
||||
* @author pangu
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(JeroRedisProperties.PREFIX)
|
||||
public class JeroRedisProperties {
|
||||
/**
|
||||
* 前缀
|
||||
*/
|
||||
public static final String PREFIX = "spring.redis";
|
||||
/**
|
||||
* 是否开启Lettuce
|
||||
*/
|
||||
private Boolean enable = true;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.jero.boot.starter.redis.service;
|
||||
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import lombok.Data;
|
||||
import com.jero.boot.starter.redis.listener.JeroRedisListerer;
|
||||
import com.jero.common.base.BaseMap;
|
||||
import com.jero.common.constant.GlobalConstants;
|
||||
import com.jero.common.util.SpringContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Data
|
||||
public class RedisReceiver {
|
||||
|
||||
|
||||
/**
|
||||
* 接受消息并调用业务逻辑处理器
|
||||
*
|
||||
* @param params
|
||||
*/
|
||||
public void onMessage(BaseMap params) {
|
||||
Object handlerName = params.get(GlobalConstants.HANDLER_NAME);
|
||||
JeroRedisListerer messageListener = SpringContextHolder.getHandler(handlerName.toString(), JeroRedisListerer.class);
|
||||
if (ObjectUtil.isNotEmpty(messageListener)) {
|
||||
messageListener.onMessage(params);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user