Commit 73720f71 authored by qinxunjia's avatar qinxunjia

优化逻辑

parent a8064744
...@@ -42,6 +42,11 @@ ...@@ -42,6 +42,11 @@
<version>2.1.1</version> <version>2.1.1</version>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- MySQL --> <!-- MySQL -->
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
......
...@@ -3,8 +3,9 @@ package com.bgy; ...@@ -3,8 +3,9 @@ package com.bgy;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan(" com.bgy.sms.repository.mapper") @MapperScan(" com.bgy.sms.repository.mapper")
public class Application { public class Application {
......
package com.bgy.config;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DB {
/**
* 切换数据源名称
*/
DataSourceType value() default DataSourceType.DB1;
}
\ No newline at end of file
package com.bgy.config;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Objects;
@Aspect
//配置加载顺序
@Order(1)
@Component
public class DataSourceAspect {
@Pointcut("@annotation(com.bgy.config.DB)")
public void doPointCut() {
}
@Around("doPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
DB dataSource = getDataSource(point);
if (!Objects.isNull(dataSource)) {
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
try {
return point.proceed();
} finally {
// 在执行方法之后 销毁数据源
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
/**
* 获取@DB注解
*/
public DB getDataSource(ProceedingJoinPoint point) {
//获得当前访问的class
Class<? extends Object> className = point.getTarget().getClass();
// 判断是否存在@DateBase注解
if (className.isAnnotationPresent(DB.class)) {
//获取注解
DB targetDataSource = className.getAnnotation(DB.class);
return targetDataSource;
}
Method method = ((MethodSignature) point.getSignature()).getMethod();
DB dataSource = method.getAnnotation(DB.class);
return dataSource;
}
}
\ No newline at end of file
package com.bgy.config;
public enum DataSourceType {
/**数据源1*/
DB1,
/**数据源2*/
DB2
}
\ No newline at end of file
package com.bgy.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
public class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
\ No newline at end of file
package com.bgy.config;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DynamicDataSourceContextHolder {
/**
* 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
* 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
*/
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
/**
* 设置数据源的变量
*/
public static void setDataSourceType(String dsType)
{
log.info("切换到{}数据源", dsType);
CONTEXT_HOLDER.set(dsType);
}
/**
* 获得数据源的变量
*/
public static String getDataSourceType()
{
return CONTEXT_HOLDER.get();
}
/**
* 清空数据源变量
*/
public static void clearDataSourceType()
{
CONTEXT_HOLDER.remove();
}
}
\ No newline at end of file
package com.bgy.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class HikariConfig {
@Bean(name = "dataSourceDb1")
@ConfigurationProperties("spring.datasource.db1")
public DataSource dataSourceDb1(HikariProperties properties)
{
//创建数据源
HikariDataSource dataSource = DataSourceBuilder.create().type(HikariDataSource.class).build();
//数据源配置
return properties.dataSource(dataSource);
}
@Bean(name = "dataSourceDb2")
@ConfigurationProperties("spring.datasource.db2")
@ConditionalOnProperty(prefix = "spring.datasource.db2", name = "enabled", havingValue = "true")
public DataSource dataSourceDb2(HikariProperties properties)
{
HikariDataSource dataSource = DataSourceBuilder.create().type(HikariDataSource.class).build();
return properties.dataSource(dataSource);
}
@Primary
@Bean(name = "dynamicDataSource")
public DynamicDataSource dataSource( DataSource dataSourceDb1,
DataSource dataSourceDb2)
{
//动态数据源
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.DB1.name(), dataSourceDb1);
targetDataSources.put(DataSourceType.DB2.name(), dataSourceDb2);
return new DynamicDataSource(dataSourceDb1, targetDataSources);
}
}
\ No newline at end of file
package com.bgy.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HikariProperties {
//获取Application.yml中的连接池配置
@Value("${spring.datasource.hikari.minimumIdle}")
private int minIdle;
@Value("${spring.datasource.hikari.maximumPoolSize}")
private int maxPoolSize;
@Value("${spring.datasource.hikari.idleTimeout}")
private int idleTimeout;
@Value("${spring.datasource.hikari.maxLifetime}")
private int maxLifetime;
@Value("${spring.datasource.hikari.connectionTimeout}")
private int connectionTimeout;
//数据源初始化
public HikariDataSource dataSource(HikariDataSource dataSource) {
//连接超时时间设置
dataSource.setConnectionTimeout(connectionTimeout);
//连接空闲生命周期设置
dataSource.setIdleTimeout(idleTimeout);
//连接池允许的最大连接数量
dataSource.setMaximumPoolSize(maxPoolSize);
//检查空余连接优化连接池设置时间,单位毫秒
dataSource.setMaxLifetime(maxLifetime);
//连接池保持最小空余连接数量
dataSource.setMinimumIdle(minIdle);
return dataSource;
}
}
\ No newline at end of file
...@@ -33,19 +33,19 @@ public class BgyApi { ...@@ -33,19 +33,19 @@ public class BgyApi {
return response; return response;
} }
@GetMapping("/report") // @GetMapping("/report")
public String report(ReportDto report) { // public String report(ReportDto report) {
log.info("回送报告接口入参:{}", JSONObject.toJSONString(report)); // log.info("回送报告接口入参:{}", JSONObject.toJSONString(report));
String response = "success"; // String response = "success";
try { // try {
// CLBizResponse responses = chuangLanSmsService.report(report); //// CLBizResponse responses = chuangLanSmsService.report(report);
} catch (Exception e) { // } catch (Exception e) {
log.error("处理回执逻辑异常:", e); // log.error("处理回执逻辑异常:", e);
response = "fail"; // response = "fail";
} // }
log.info("碧桂园异步通知接口出参:{}", response); // log.info("碧桂园异步通知接口出参:{}", response);
return response; // return response;
} // }
//
} }
package com.bgy.sms.channel.api; package com.bgy.sms.channel.api;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.bgy.sms.channel.bgy.config.BgySMSConfig;
import com.bgy.sms.channel.dmHub.config.DmHubConfig; import com.bgy.sms.channel.dmHub.config.DmHubConfig;
import com.bgy.sms.channel.dto.*; import com.bgy.sms.channel.dto.*;
import com.bgy.sms.config.ResponseCode; import com.bgy.sms.config.ResponseCode;
import com.bgy.sms.repository.domain.SmsTemplateInfo;
import com.bgy.sms.service.MessageService; import com.bgy.sms.service.MessageService;
import com.bgy.sms.service.SmsTemplateService;
import com.bgy.util.HttpUtil;
import com.bgy.util.Md5Util; import com.bgy.util.Md5Util;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
@RestController @RestController
@RequestMapping() @RequestMapping()
...@@ -28,8 +20,6 @@ public class DmHubApi { ...@@ -28,8 +20,6 @@ public class DmHubApi {
@Autowired @Autowired
private MessageService messageService; private MessageService messageService;
@Autowired
private SmsTemplateService smsTemplateService;
@GetMapping("/ping") @GetMapping("/ping")
public String ping() { public String ping() {
...@@ -53,8 +43,6 @@ public class DmHubApi { ...@@ -53,8 +43,6 @@ public class DmHubApi {
return new DmHubResponse("555", "接口请求签名校验不通过"); return new DmHubResponse("555", "接口请求签名校验不通过");
} }
response = messageService.createTemplate(params); response = messageService.createTemplate(params);
} catch (Exception e) { } catch (Exception e) {
log.error("创建模板短信异常", e); log.error("创建模板短信异常", e);
response = new DmHubResponse("999", "创建模板短信异常"); response = new DmHubResponse("999", "创建模板短信异常");
...@@ -101,8 +89,7 @@ public class DmHubApi { ...@@ -101,8 +89,7 @@ public class DmHubApi {
if (!checkResult) { if (!checkResult) {
return new DmHubResponse("555", "接口请求签名校验不通过"); return new DmHubResponse("555", "接口请求签名校验不通过");
} }
response = messageService.batchSendBatch(request);
response = messageService.batchSendOneByOne(request);
response.setCode(response.getError().getString("errorCode")); response.setCode(response.getError().getString("errorCode"));
} catch (Exception e) { } catch (Exception e) {
log.error("发送批量短信异常", e); log.error("发送批量短信异常", e);
...@@ -149,15 +136,4 @@ public class DmHubApi { ...@@ -149,15 +136,4 @@ public class DmHubApi {
return response; return response;
} }
public static void main(String[] args) {
String z = "{\"err\":\"成功\",\"package\":\"{\\\"data\\\":\\\"8fff70a0-d751-4d2b-b4c6-17edec541ec7\\\"}\",\"ret\":\"0\"} ";
JSONObject retJson = JSONObject.parseObject(z);
String data = retJson.getString("package");
JSONObject retJson2 = JSONObject.parseObject(data);
String data2 = retJson2.getString("data");
//String retStr = HttpUtil.sendPost(BgySMSConfig.url, JSONObject.toJSONString(z));
System.out.println(data2);
}
} }
...@@ -25,7 +25,7 @@ import java.util.List; ...@@ -25,7 +25,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
@SuppressWarnings("DuplicatedCode") @SuppressWarnings({"DuplicatedCode", "Duplicates"})
@Service @Service
public class BgySmsServiceImpl implements BgySmsService { public class BgySmsServiceImpl implements BgySmsService {
...@@ -51,7 +51,6 @@ public class BgySmsServiceImpl implements BgySmsService { ...@@ -51,7 +51,6 @@ public class BgySmsServiceImpl implements BgySmsService {
public CLBizResponse sendSms(String mobile, String content, String areaId, String api) throws Exception { public CLBizResponse sendSms(String mobile, String content, String areaId, String api) throws Exception {
log.info("进入碧桂园短信发送接口"); log.info("进入碧桂园短信发送接口");
String appId = BgySMSConfig.appId; String appId = BgySMSConfig.appId;
// String areaId = BgySMSConfig.areaId;
String securityCode = BgySMSConfig.securityCode; String securityCode = BgySMSConfig.securityCode;
String url = BgySMSConfig.url; String url = BgySMSConfig.url;
if (api == null) { if (api == null) {
...@@ -88,10 +87,8 @@ public class BgySmsServiceImpl implements BgySmsService { ...@@ -88,10 +87,8 @@ public class BgySmsServiceImpl implements BgySmsService {
public CLBizResponse sendBatchSms(List<JSONObject> data, String areaId, String api, String templateId) throws Exception { public CLBizResponse sendBatchSms(List<JSONObject> data, String areaId, String api, String templateId) throws Exception {
log.info("进入碧桂园短信发送接口"); log.info("进入碧桂园短信发送接口");
String appId = BgySMSConfig.appId; String appId = BgySMSConfig.appId;
// String areaId = BgySMSConfig.areaId;
String securityCode = BgySMSConfig.securityCode; String securityCode = BgySMSConfig.securityCode;
String url = BgySMSConfig.url; String url = BgySMSConfig.url;
// String api = BgySMSConfig.api;
Map<String, Object> requestParams = new HashMap<>(); Map<String, Object> requestParams = new HashMap<>();
requestParams.put("api", api); requestParams.put("api", api);
requestParams.put("appId", appId); requestParams.put("appId", appId);
...@@ -99,7 +96,7 @@ public class BgySmsServiceImpl implements BgySmsService { ...@@ -99,7 +96,7 @@ public class BgySmsServiceImpl implements BgySmsService {
requestParams.put("areaId", areaId); requestParams.put("areaId", areaId);
requestParams.put("templateId", templateId); requestParams.put("templateId", templateId);
requestParams.put("data", data); requestParams.put("data", data);
log.info("碧桂园短信接口参数:{}", requestParams);//TODO log.info("碧桂园短信接口参数:{}", requestParams);
String reqStr = JSONObject.toJSONString(requestParams); String reqStr = JSONObject.toJSONString(requestParams);
String retStr = SendSmsUtil.sendSmsByPost(url, reqStr); String retStr = SendSmsUtil.sendSmsByPost(url, reqStr);
log.info("碧桂园短信接口返回信息:{}", retStr); log.info("碧桂园短信接口返回信息:{}", retStr);
...@@ -153,11 +150,8 @@ public class BgySmsServiceImpl implements BgySmsService { ...@@ -153,11 +150,8 @@ public class BgySmsServiceImpl implements BgySmsService {
public CLBizResponse createTemplate(String content, String account, String templateType, String pkID) throws Exception { public CLBizResponse createTemplate(String content, String account, String templateType, String pkID) throws Exception {
log.info("进入碧桂园创建模板接口"); log.info("进入碧桂园创建模板接口");
String appId = BgySMSConfig.appId; String appId = BgySMSConfig.appId;
// String areaId = BgySMSConfig.areaId;
String securityCode = BgySMSConfig.securityCode; String securityCode = BgySMSConfig.securityCode;
Map<String, String> param = new HashMap<>(); Map<String, String> param = new HashMap<>();
param.put("api", "AddTemplate");//TODO param.put("api", "AddTemplate");//TODO
param.put("appid", appId); param.put("appid", appId);
param.put("security", Md5Util.encrypt(appId + securityCode.toUpperCase())); param.put("security", Md5Util.encrypt(appId + securityCode.toUpperCase()));
......
package com.bgy.sms.config;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*  * @ClassName: IPUtil
*  * @version 1.0 
*  * @Desc: Ip工具类
*  * @author huaping hu
*  * @date 2016年6月1日下午5:26:56
*  * @history v1.0
*  *
*  
*/
@Slf4j
public class IPUtil {
/**
*  
* 描述:获取IP地址
*
* @param request
* @return
* @author huaping hu 
* @date 2016年6月1日下午5:25:44
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
\ No newline at end of file
//package com.bgy.sms.config;
//
//import com.bgy.util.id.Id;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.PreDestroy;
//import java.util.Timer;
//import java.util.TimerTask;
//import java.util.concurrent.TimeUnit;
//
//@Service("machineIdUtil")
//@Slf4j
//public class MachineIdUtil {
// //日誌
// /**
// * redis 实例
// */
// @Autowired
// private StringRedisTemplate redisTemplate;
// /**
// * 机器id
// */
// public static Integer machine_id;
// /**
// * 本地ip地址
// */
// private static String localIp;
// private static TimeUnit timeUnit = TimeUnit.DAYS;
//
// /**
// * hash机器IP初始化一个机器ID
// */
// @PostConstruct
// public void initMachineId() throws Exception {
//// localIp = IpUtil.getInet4Address();
//
// Long ip_ = Long.parseLong(localIp.replaceAll("\\.", ""));
// //这里取128,为后续机器Ip调整做准备。
// machine_id = ip_.hashCode() % 128;
// //创建一个机器ID
// createMachineId();
// log.info("初始化 machine_id :{}", machine_id);
// Id.initMachineId(machine_id);
// }
//
// /**
// * 容器销毁前清除注册记录
// */
// @PreDestroy
// public void destroyMachineId() {
// redisTemplate.delete("OPLOG_MACHINE_ID_KEY" + machine_id);
// }
//
//
// /**
// * 主方法:获取一个机器id
// *
// * @return
// */
// public Integer createMachineId() {
// try {
// //向redis注册,并设置超时时间
// Boolean aBoolean = registMachine(machine_id);
// //注册成功
// if (aBoolean) {
// //启动一个线程更新超时时间
// updateExpTimeThread();
// //返回机器Id
// return machine_id;
// }
// //检查是否被注册满了.不能注册,就直接返回
// if (!checkIfCanRegist()) {
// //注册满了,加一个报警
// return machine_id;
// }
// //递归调用
// createMachineId();
// } catch (Exception e) {
// getRandomMachineId();
// return machine_id;
// }
// getRandomMachineId();
// return machine_id;
// }
//
// /**
// * 检查是否被注册满了
// *
// * @return
// */
// private Boolean checkIfCanRegist() {
// Boolean flag = true;
// //判断0~127这个区间段的机器IP是否被占满
// for (int i = 0; i <= 127; i++) {
// flag = redisTemplate.hasKey("OPLOG_MACHINE_ID_KEY" + i);
// //如果不存在。说明还可以继续注册。直接返回i
// if (!flag) {
// machine_id = i;
// break;
// }
// }
// return !flag;
// }
//
// /**
// * 1.更新超時時間
// * 注意,更新前检查是否存在机器ip占用情况
// */
// private void updateExpTimeThread() {
// //开启一个线程执行定时任务:
// //1.每23小时更新一次超时时间
// new Timer(localIp).schedule(new TimerTask() {
// @Override
// public void run() {
// //检查缓存中的ip与本机ip是否一致,一致則更新時間,不一致則重新取一個机器ID
// Boolean b = checkIsLocalIp(String.valueOf(machine_id));
// if (b) {
// redisTemplate.expire("OPLOG_MACHINE_ID_KEY" + machine_id, 1, timeUnit);
// } else {
// //重新生成机器ID,并且更改雪花中的机器ID
// getRandomMachineId();
// //重新生成并注册机器id
// createMachineId();
// //更改雪花中的机器ID
// Id.initMachineId(machine_id);
// //結束當前任務
// log.info("Timer->thread->name:{}", Thread.currentThread().getName());
// this.cancel();
// }
// }
// }, 10 * 1000, 1000 * 60 * 60 * 23);
// }
//
// /**
// * 获取1~127随机数
// */
// public void getRandomMachineId() {
// machine_id = (int) (Math.random() * 127);
// }
//
// /**
// * 机器ID顺序获取
// */
// public void incMachineId() {
// if (machine_id >= 127) {
// machine_id = 0;
// } else {
// machine_id += 1;
// }
// }
//
// /**
// * @param mechineId
// * @return
// */
// private Boolean checkIsLocalIp(String mechineId) {
// String ip = redisTemplate.opsForValue().get("OPLOG_MACHINE_ID_KEY" + mechineId);
// log.info("checkIsLocalIp->ip:{}", ip);
// return localIp.equals(ip);
// }
//
// /**
// * 1.注册机器
// * 2.设置超时时间
// *
// * @param mechineId 取值为0~127
// * @return
// */
// private Boolean registMachine(Integer mechineId) throws Exception {
// redisTemplate.opsForValue().set("OPLOG_MACHINE_ID_kEY" + mechineId, localIp, 1, TimeUnit.DAYS);
// return true;
// }
//
//
//}
\ No newline at end of file
package com.bgy.sms.config; package com.bgy.sms.config;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
...@@ -10,30 +8,6 @@ import org.springframework.context.annotation.Configuration; ...@@ -10,30 +8,6 @@ import org.springframework.context.annotation.Configuration;
@Configuration @Configuration
//@MapperScan("com.baomidou.springboot.mapper*")//这个注解,作用相当于下面的@Bean MapperScannerConfigurer,2者配置1份即可 //@MapperScan("com.baomidou.springboot.mapper*")//这个注解,作用相当于下面的@Bean MapperScannerConfigurer,2者配置1份即可
public class MybatisPlusConfig { public class MybatisPlusConfig {
/**
* SQL输出拦截器,性能分析器,不建议生产环境使用,开发环境使用(方便)
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
//sql格式化
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
/**
* mybatis-plus分页插件<br>
* 文档:http://mp.baomidou.com<br>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//paginationInterceptor.setDialectType("mysql"); //指定数据库类型,不写自动匹配
return paginationInterceptor;
};
@Bean @Bean
public MapperScannerConfigurer mapperScannerConfigurer() { public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer(); MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
......
...@@ -8,6 +8,7 @@ public enum ResponseCode { ...@@ -8,6 +8,7 @@ public enum ResponseCode {
SYSTEM_ERROR("99", "系统异常:"), SYSTEM_ERROR("99", "系统异常:"),
NO_TEMPLATE("error", "未找到短信模板"), NO_TEMPLATE("error", "未找到短信模板"),
DMHUB_NO_DATA("error", "没有请求数据"), DMHUB_NO_DATA("error", "没有请求数据"),
NO_USER_ID("error", "当前登录账号未获取到售楼系统的userId"),
// 渠道异常错误 // 渠道异常错误
UPSTREAM_FAIL("US01", "渠道交易失败"), UPSTREAM_FAIL("US01", "渠道交易失败"),
......
package com.bgy.sms.repository.mapper;
import org.apache.ibatis.annotations.Param;
public interface XiaoShuMapper {
String getLoginNameByTempId(@Param("tempId") String templateId);
void updateSmsTemplateStatus(@Param("tempId") String templateId);
}
...@@ -26,7 +26,7 @@ public interface MessageService { ...@@ -26,7 +26,7 @@ public interface MessageService {
* @param requestDTO * @param requestDTO
* @return * @return
*/ */
DmHubResponse batchSendOneByOne(DmHubBatchSendRequest requestDTO); DmHubResponse batchSendBatch(DmHubBatchSendRequest requestDTO);
DmHubResponse sendCode(DmHubCodeRequest params); DmHubResponse sendCode(DmHubCodeRequest params);
} }
package com.bgy.sms.service;
public interface XiaoShuService {
String selectUserIdByTemplate(String templateId);
void updateSmsTemplateStatus(String templateId);
}
...@@ -44,6 +44,9 @@ public class MessageServiceImpl implements MessageService { ...@@ -44,6 +44,9 @@ public class MessageServiceImpl implements MessageService {
@Autowired @Autowired
private SysRecordService sysRecordService; private SysRecordService sysRecordService;
@Autowired
private XiaoShuService xiaoShuService;
/** /**
* 短信模板创建 * 短信模板创建
* *
...@@ -65,7 +68,7 @@ public class MessageServiceImpl implements MessageService { ...@@ -65,7 +68,7 @@ public class MessageServiceImpl implements MessageService {
// 替换模板格式,保存适合碧桂园发送短信的模板,避免发送时修改模板格式 // 替换模板格式,保存适合碧桂园发送短信的模板,避免发送时修改模板格式
TemplateChangeBean bean = dmHub2BgyTemplateSend(templateContent); TemplateChangeBean bean = dmHub2BgyTemplateSend(templateContent);
String chuanglanSend = bean.getUpSendStr(); String bgySendStr = bean.getUpSendStr();
String params = bean.getParams().toString(); String params = bean.getParams().toString();
SmsTemplateInfo dbInfo = smsTemplateService.selectOne(new EntityWrapper<SmsTemplateInfo>().eq("dm_template_id", templateId)); SmsTemplateInfo dbInfo = smsTemplateService.selectOne(new EntityWrapper<SmsTemplateInfo>().eq("dm_template_id", templateId));
if (dbInfo != null) { if (dbInfo != null) {
...@@ -83,41 +86,36 @@ public class MessageServiceImpl implements MessageService { ...@@ -83,41 +86,36 @@ public class MessageServiceImpl implements MessageService {
info.setDateCreated(new Date()); info.setDateCreated(new Date());
info.setLastUpdated(new Date()); info.setLastUpdated(new Date());
info.setLastUpdated(new Date()); info.setLastUpdated(new Date());
info.setUpContent(chuanglanSend); info.setUpContent(bgySendStr);
info.setParams(params); info.setParams(params);
boolean insert = smsTemplateService.insert(info); boolean insert = smsTemplateService.insert(info);
if (!insert) { if (!insert) {
log.error("模板插入DB异常:【{}】", JSONObject.toJSONString(info)); log.error("模板插入DB异常:【{}】", JSONObject.toJSONString(info));
return new DmHubResponse(ResponseCode.SYSTEM_ERROR); return new DmHubResponse(ResponseCode.SYSTEM_ERROR);
} else { } else {
String appId = BgySMSConfig.appId;
String securityCode = BgySMSConfig.securityCode;
String pkID = info.getId() + ""; String pkID = info.getId() + "";
String content = info.getContent();
String TEMPLATETYPE = ""; String TEMPLATETYPE = "";
if ("marketing".equals(smsType)) { if ("marketing".equals(smsType)) {
TEMPLATETYPE = "52"; TEMPLATETYPE = "52";
} else { } else {
TEMPLATETYPE = "49"; TEMPLATETYPE = "49";
} }
String account = "SZH003";
CLBizResponse response = new CLBizResponse(); CLBizResponse response = new CLBizResponse();
String account = xiaoShuService.selectUserIdByTemplate(templateId);
response = bgySmsService.createTemplate(content, account, TEMPLATETYPE, pkID); if (StringUtils.isBlank(account)) {
return new DmHubResponse(ResponseCode.NO_USER_ID);
}
xiaoShuService.updateSmsTemplateStatus(templateId);
response = bgySmsService.createTemplate(bgySendStr, account, TEMPLATETYPE, pkID);
String code = response.getCode(); String code = response.getCode();
String msg = response.getMsg(); String msg = response.getMsg();
if (code.equals(ResponseCode.SUCCESS.getCode())) { if (code.equals(ResponseCode.SUCCESS.getCode())) {
SmsTemplateInfo updateInfo = new SmsTemplateInfo();
info.setTemplateRecordId(msg); updateInfo.setTemplateRecordId(msg);
info.setId(Long.parseLong(pkID)); updateInfo.setId(Long.parseLong(pkID));
smsTemplateService.updateById(info); smsTemplateService.updateById(updateInfo);
return new DmHubResponse(ResponseCode.SUCCESS); return new DmHubResponse(ResponseCode.SUCCESS);
} else { } else {
return new DmHubResponse(code, msg); return new DmHubResponse(code, msg);
} }
} }
...@@ -156,7 +154,6 @@ public class MessageServiceImpl implements MessageService { ...@@ -156,7 +154,6 @@ public class MessageServiceImpl implements MessageService {
String t = g; String t = g;
g = Matcher.quoteReplacement(g); g = Matcher.quoteReplacement(g);
g = escapeRegex(g); g = escapeRegex(g);
// upSendStr = upSendStr.replaceAll(g, "\\{\\$var\\}");
upSendStr = upSendStr.replaceAll(g, "\\$\\$"); upSendStr = upSendStr.replaceAll(g, "\\$\\$");
if (t.contains("${surl!")) { if (t.contains("${surl!")) {
// 短链没传长度,固定长度20 // 短链没传长度,固定长度20
...@@ -221,11 +218,9 @@ public class MessageServiceImpl implements MessageService { ...@@ -221,11 +218,9 @@ public class MessageServiceImpl implements MessageService {
} }
// 2、根据请求信息获取用户的手机号码(此处不考虑配置DMHUB系统不是SMS的情况),直接拿请求体中的_audienceId字段值,该值为手机号码 // 2、根据请求信息获取用户的手机号码(此处不考虑配置DMHUB系统不是SMS的情况),直接拿请求体中的_audienceId字段值,该值为手机号码
// 模板参数占位符 // 模板参数占位符
if (templateInfo.getStatus() .equals("abnormal")) { if (templateInfo.getStatus().equals("abnormal")) {
return new DmHubResponse("1001", "当前模板暂未审核通过,请重新选择"); return new DmHubResponse("1001", "短信模板正在审核中,请稍后重试");
} }
String params = templateInfo.getParams(); String params = templateInfo.getParams();
JSONArray paramsArr = JSONArray.parseArray(params); JSONArray paramsArr = JSONArray.parseArray(params);
String smsType = templateInfo.getType(); String smsType = templateInfo.getType();
...@@ -295,10 +290,8 @@ public class MessageServiceImpl implements MessageService { ...@@ -295,10 +290,8 @@ public class MessageServiceImpl implements MessageService {
long sysRecordInfoBatchId = IdHandler.nextId(); long sysRecordInfoBatchId = IdHandler.nextId();
sysRecordInfo.setSysBatchId(sysRecordInfoBatchId); sysRecordInfo.setSysBatchId(sysRecordInfoBatchId);
sysRecordInfo.setMobile(mobile); sysRecordInfo.setMobile(mobile);
//sysRecordInfo.setMsgId();
sysRecordInfo.setChargeNum(1); sysRecordInfo.setChargeNum(1);
sysRecordInfo.setContent(content); sysRecordInfo.setContent(content);
//sysRecordInfo.setParams();
Date date = new Date(); Date date = new Date();
sysRecordInfo.setDateCreated(date); sysRecordInfo.setDateCreated(date);
sysRecordInfo.setLastUpdated(date); sysRecordInfo.setLastUpdated(date);
...@@ -369,7 +362,7 @@ public class MessageServiceImpl implements MessageService { ...@@ -369,7 +362,7 @@ public class MessageServiceImpl implements MessageService {
@Override @Override
public DmHubResponse batchSendOneByOne(DmHubBatchSendRequest request) { public DmHubResponse batchSendBatch(DmHubBatchSendRequest request) {
String batchId = request.getBatchId(); // DM hub 批次号 String batchId = request.getBatchId(); // DM hub 批次号
String templateId = request.getTemplateId(); // 此次短信对应的模板id String templateId = request.getTemplateId(); // 此次短信对应的模板id
List<JSONObject> data = request.getData(); List<JSONObject> data = request.getData();
...@@ -379,9 +372,8 @@ public class MessageServiceImpl implements MessageService { ...@@ -379,9 +372,8 @@ public class MessageServiceImpl implements MessageService {
return new DmHubResponse("999", "短信插件未获取到模板信息"); return new DmHubResponse("999", "短信插件未获取到模板信息");
} }
if (templateInfo.getStatus() .equals("abnormal")) { if (templateInfo.getStatus().equals("abnormal")) {
return new DmHubResponse("1001", "当前模板暂未审核通过,请重新选择"); return new DmHubResponse("1001", "短信模板正在审核中,请稍后重试");
} }
String api = ""; String api = "";
if ("marketing".equals(templateInfo.getType())) { if ("marketing".equals(templateInfo.getType())) {
...@@ -512,7 +504,6 @@ public class MessageServiceImpl implements MessageService { ...@@ -512,7 +504,6 @@ public class MessageServiceImpl implements MessageService {
} else { } else {
// 变量短信 // 变量短信
Set<Map.Entry<String, List<String>>> entries = paramsMap.entrySet(); Set<Map.Entry<String, List<String>>> entries = paramsMap.entrySet();
// List<JSONObject> list = new ArrayList<>();
List<JSONObject> list = new ArrayList<>(); List<JSONObject> list = new ArrayList<>();
StringBuilder mobiles = new StringBuilder(); StringBuilder mobiles = new StringBuilder();
String content = templateInfo.getUpContent(); String content = templateInfo.getUpContent();
......
package com.bgy.sms.service.impl;
import com.bgy.config.DB;
import com.bgy.config.DataSourceType;
import com.bgy.sms.repository.mapper.XiaoShuMapper;
import com.bgy.sms.service.XiaoShuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class XiaoShuServiceImpl implements XiaoShuService {
@Autowired
private XiaoShuMapper xiaoShuMapper;
@Override
@DB(value = DataSourceType.DB2)
public String selectUserIdByTemplate(String templateId) {
String loginName = xiaoShuMapper.getLoginNameByTempId(templateId);
return loginName;
}
@Override
@DB(value = DataSourceType.DB2)
public void updateSmsTemplateStatus(String templateId) {
xiaoShuMapper.updateSmsTemplateStatus(templateId);
}
}
...@@ -9,12 +9,22 @@ server: ...@@ -9,12 +9,22 @@ server:
spring: spring:
datasource: datasource:
type: com.zaxxer.hikari.HikariDataSource db1:
url: jdbc:mysql://119.23.32.151:3306/dmhub_plugin?characterEncoding=utf8&useSSL=false jdbc-url: jdbc:mysql://119.23.32.151:3306/dmhub_plugin?characterEncoding=utf8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver driverClassName: com.mysql.cj.jdbc.Driver
username: dmp
password: Ioubuy@2019@!
enabled: true
db2:
jdbc-url: jdbc:mysql://119.23.32.151:3306/xiaoshu?characterEncoding=utf8&useSSL=false
driverClassName: com.mysql.cj.jdbc.Driver
username: dmp username: dmp
password: Ioubuy@2019@! password: Ioubuy@2019@!
enabled: true
type: com.zaxxer.hikari.HikariDataSource
hikari: hikari:
# 最小空闲链接数
minimumIdle: 5
maxLifetime: 1765000 maxLifetime: 1765000
maximumPoolSize: 20 maximumPoolSize: 20
connectionTimeout: 30000 connectionTimeout: 30000
......
...@@ -9,12 +9,22 @@ server: ...@@ -9,12 +9,22 @@ server:
spring: spring:
datasource: datasource:
type: com.zaxxer.hikari.HikariDataSource
url: ${dataSource_url} db1:
driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: ${dataSource1_url}
driverClassName: com.mysql.cj.jdbc.Driver
username: ${dataSource_username} username: ${dataSource_username}
password: ${dataSource_password} password: ${dataSource_password}
enabled: true
db2:
jdbc-url: ${dataSource2_url}
driverClassName: com.mysql.cj.jdbc.Driver
username: ${dataSource_username}
password: ${dataSource_password}
enabled: true
type: com.zaxxer.hikari.HikariDataSource
hikari: hikari:
minimumIdle: 5
maxLifetime: 1765000 maxLifetime: 1765000
maximumPoolSize: 20 maximumPoolSize: 20
connectionTimeout: 30000 connectionTimeout: 30000
......
...@@ -4,23 +4,28 @@ server: ...@@ -4,23 +4,28 @@ server:
tomcat: tomcat:
max-threads: 50 max-threads: 50
port: 15600 port: 15600
spring: spring:
datasource: datasource:
type: com.zaxxer.hikari.HikariDataSource db1:
url: jdbc:mysql://my09457h.mysql.db.pcloud.localdomain:3070/dmhub_plugin?characterEncoding=utf8&useSSL=false jdbc-url: jdbc:mysql://my09457h.mysql.db.pcloud.localdomain:3070/dmhub_plugin?characterEncoding=utf8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver driverClassName: com.mysql.cj.jdbc.Driver
username: bu00310
password: pwd$BU00310
enabled: true
db2:
jdbc-url: jdbc:mysql://my09457h.mysql.db.pcloud.localdomain:3070/xiaoshu?characterEncoding=utf8&useSSL=false
driverClassName: com.mysql.cj.jdbc.Driver
username: bu00310 username: bu00310
password: pwd$BU00310 password: pwd$BU00310
enabled: true
type: com.zaxxer.hikari.HikariDataSource
hikari: hikari:
minimumIdle: 5
maxLifetime: 1765000 maxLifetime: 1765000
maximumPoolSize: 20 maximumPoolSize: 20
connectionTimeout: 30000 connectionTimeout: 30000
idleTimeout: 600000 idleTimeout: 600000
pool-name: dmhub-plug-pool pool-name: dmhub-plug-pool
redis: redis:
database: 0 database: 0
host: rs67xf4p.redisrep.db.pcloud.localdomain host: rs67xf4p.redisrep.db.pcloud.localdomain
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bgy.sms.repository.mapper.XiaoShuMapper">
<select id="getLoginNameByTempId" parameterType="string" resultType="string">
select A.login_name from `user` as A
join sms_template as B on A.id = B.creator_id
where B.id = #{tempId}
</select>
<update id="updateSmsTemplateStatus" parameterType="string">
update sms_template set status = 'applying' where id = #{tempId}
</update>
</mapper>
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