Commit 0ddcf6f4 by levphon

新e盾通知服务

0 parents
Showing 27 changed files with 1501 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>glsx-ne-shield</artifactId>
<groupId>com.glsx</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<artifactId>glsx-ne-shield-notifycenter</artifactId>
<dependencies>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-sms</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mail</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.glsx</groupId>-->
<!-- <artifactId>rest-admin-wechat</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-mybatis</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-kafka</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-im</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>glsx-ne-shield-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx;
import cn.com.glsx.notify.netty.NettyServer;
import com.glsx.plat.context.EnableRestAdmin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
/**
* @author payu
*/
@EnableRestAdmin
@EnableDiscoveryClient
@EnableTransactionManagement
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
//启动NettyServer服务端
NettyServer nettyServer = new NettyServer();
nettyServer.run();
}
@PostConstruct
void started() {
TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));
}
}
package cn.com.glsx.notify.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
//@Configuration
public class WebSocketConfig {
// @Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.api;
import cn.com.glsx.admin.api.NotifyCenterFeignClient;
import cn.com.glsx.admin.services.notifyservice.model.MailTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.PCTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.SmsTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.WechatTemplateMessageDTO;
import cn.com.glsx.notify.modules.service.MailService;
import cn.com.glsx.notify.modules.service.PCService;
import cn.com.glsx.notify.modules.service.SmsService;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping(value = "/api/notify")
class NotifyApiController implements NotifyCenterFeignClient {
@Autowired
private SmsService smsService;
@Autowired
private MailService mailService;
@Autowired
private PCService pcService;
// @Autowired
// private WeixinService weixinService;
@Override
@PostMapping(value = "/sendSms")
public R sendSms(@RequestBody SmsTemplateMessageDTO messageDTO) {
smsService.sendSms(messageDTO.getPhone(), messageDTO.getTemplate(), messageDTO.getArgs().values());
return R.ok();
}
@Override
@PostMapping(value = "/sendMail")
public R sendMail(@RequestBody MailTemplateMessageDTO messageDTO) {
Map<String, Object> args = new HashMap<>();
args.put("arg1", "刘宇峰");
args.put("arg2", "B73493098765");
args.put("arg3", 1234);
mailService.sendSimpleMail("liuyf@didihu.com.cn", "notifycenter test", "MAIL_TEMPLATE_ORDER_PAID_NOTIFY_OPERATOR", args.values());
return R.ok();
}
@Override
@PostMapping(value = "/sendPC")
public R sendPC(@RequestBody PCTemplateMessageDTO messageDTO) {
// TODO: 2020/9/21 名称约束
// 2020/9/21 kafka消息队列
pcService.sendMessage(messageDTO);
return R.ok();
}
@Override
@PostMapping(value = "/sendWechat")
public R sendWechat(@RequestBody WechatTemplateMessageDTO messageDTO) {
//weixinService.push(messageDTO.getAppid(), messageDTO);
return R.ok();
}
}
package cn.com.glsx.notify.modules.controller;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@Component
@EqualsAndHashCode
@ServerEndpoint(value = "/ws/asset")
public class WebSocketServer {
@PostConstruct
public void init() {
log.info("websocket 加载");
}
private Session session;
public static CopyOnWriteArraySet<WebSocketServer> SocketSet = new CopyOnWriteArraySet<>();
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
// concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<>();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
SessionSet.add(session);
SocketSet.add(this);
this.session = session;
// 在线数加1
int cnt = OnlineCount.incrementAndGet();
log.info(String.valueOf(session.getRequestURI()));
log.info("有连接加入,当前连接数为:{},sessionId={}", cnt, session.getId());
SendMessage(session, "连接成功");
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
SocketSet.remove(this);
int cnt = OnlineCount.decrementAndGet();
log.info("有连接关闭,当前连接数为:{}", cnt);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:{}", message);
SendMessage(session, "收到消息,消息内容:" + message);
}
/**
* 出现错误
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
error.printStackTrace();
}
/**
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
*
* @param session
* @param message
*/
public static void SendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("发送消息出错:{}", e.getMessage());
e.printStackTrace();
}
}
/**
* 群发消息
*
* @param message
* @throws IOException
*/
public static void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
if (session.isOpen()) {
SendMessage(session, message);
}
}
}
/**
* 指定Session发送消息
*
* @param sessionId
* @param message
* @throws IOException
*/
public static void SendMessage(String message, String sessionId) throws IOException {
Session session = null;
for (Session s : SessionSet) {
if (s.getId().equals(sessionId)) {
session = s;
break;
}
}
if (session != null) {
SendMessage(session, message);
} else {
log.warn("没有找到你指定ID的会话:{}", sessionId);
}
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
}
package cn.com.glsx.notify.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Table;
@Data
@Table(name = "t_message_log")
public class MessageLog extends BaseEntity {
@Column(name = "from_user")
private String fromUser;
@Column(name = "to_user")
private String toUser;
private String template;
private String subject;
private String content;
private String attachment;
private String type;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.entity;
import com.glsx.plat.mybatis.base.BaseEntity;
import lombok.Data;
import javax.persistence.Table;
@Data
@Table(name = "t_message_template")
public class MessageTemplate extends BaseEntity {
private String template;
private String subject;
private String content;
private String type;
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.kafka;
import cn.com.glsx.notify.modules.controller.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Optional;
import static cn.com.glsx.notify.modules.controller.WebSocketServer.SocketSet;
/**
* @author payu
*/
@Slf4j
@Component
public class MessageConsumer {
@KafkaListener(id = "messageConsumer",
topics = "#{'${topic.message.application}'.split(',')}",
errorHandler = "consumerAwareErrorHandler")
public void listener(ConsumerRecord<?, ?> record) {
//errorHandler异常处理器注解里面使用的也是bean的名称
//判断是否为null
Optional<?> kafkaMessage = Optional.ofNullable(record.value());
if (kafkaMessage.isPresent()) {
//得到Optional实例中的值
Object message = kafkaMessage.get();
log.info("消费消息:" + message);
try {
for (WebSocketServer socketServer : SocketSet) {
socketServer.sendMessage(message.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package cn.com.glsx.notify.modules.mapper;
import cn.com.glsx.notify.modules.entity.MessageLog;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MessageLogMapper extends CommonBaseMapper<MessageLog> {
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.mapper;
import cn.com.glsx.notify.modules.entity.MessageTemplate;
import com.glsx.plat.mybatis.mapper.CommonBaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface MessageTemplateMapper extends CommonBaseMapper<MessageTemplate> {
MessageTemplate findByTemplate(@Param("template") String template);
MessageTemplate findByTemplateAndType(@Param("template") String template, @Param("type") String type);
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.notify.modules.entity.MessageLog;
import cn.com.glsx.notify.modules.entity.MessageTemplate;
import cn.com.glsx.notify.modules.mapper.MessageLogMapper;
import cn.com.glsx.notify.modules.mapper.MessageTemplateMapper;
import com.glsx.plat.mail.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
/**
* @author payu
*/
@Service
public class MailService {
@Autowired
private MailUtils mailUtils;
@Autowired
private MessageLogMapper messageLogMapper;
@Autowired
private MessageTemplateMapper messageTemplateMapper;
/**
* 发送文本邮件
*
* @param to 收件人
* @param subject 主题
* @param template 内容
* @param arg 参数
*/
public void sendSimpleMail(String to, String subject, String template, Object... arg) {
MessageTemplate mt = messageTemplateMapper.findByTemplate(template);
if (mt == null) return;
String content = MessageFormat.format(mt.getContent(), arg);
mailUtils.sendTextMail(to, subject, content);
MessageLog log = new MessageLog();
log.setSubject(subject);
log.setToUser(to);
log.setContent(content);
log.setTemplate(template);
log.setType(mt.getType());
messageLogMapper.insert(log);
}
/**
* 发送HTML邮件
*
* @param to 收件人
* @param subject 主题
* @param content 内容
*/
void sendHtmlMail(String to, String subject, String content) throws MessagingException {
mailUtils.sendHtmlMail(to, subject, content);
}
/**
* 发送带附件的邮件
*
* @param to 收件人
* @param subject 主题
* @param template 内容
* @param filepaths 附件
*/
public void sendAttachmentsMail(String to, String subject, String template, List<Map<String, String>> filepaths, Object... arg) throws Exception {
MessageTemplate mt = messageTemplateMapper.findByTemplate(template);
if (mt == null) return;
String content = MessageFormat.format(mt.getContent(), arg);
mailUtils.sendAttachmentMail(to, subject, content, filepaths);
}
}
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.admin.services.notifyservice.model.PCTemplateMessageDTO;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import javax.annotation.Resource;
/**
* @author payu
*/
@Slf4j
@Service
public class PCService {
@Resource
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(PCTemplateMessageDTO messageDTO) {
// 发送消息,json 作为消息体
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(messageDTO.getApplication() + "_topic", JSONObject.toJSONString(messageDTO));
// 监听回调
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
log.info("## Send message success ...");
}
@Override
public void onFailure(Throwable throwable) {
log.error("## Send message fail ...{}", throwable.getMessage());
}
});
}
}
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.notify.modules.entity.MessageLog;
import cn.com.glsx.notify.modules.entity.MessageTemplate;
import cn.com.glsx.notify.modules.mapper.MessageLogMapper;
import cn.com.glsx.notify.modules.mapper.MessageTemplateMapper;
import cn.com.glsx.notify.modules.utils.SmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.MessageFormat;
/**
* @author payu
*/
@Service
public class SmsService {
@Autowired
private SmsUtils smsUtils;
@Autowired
private MessageLogMapper messageLogMapper;
@Autowired
private MessageTemplateMapper messageTemplateMapper;
public void sendSms(String phone, String template, Object... arg) {
MessageTemplate mt = messageTemplateMapper.findByTemplate(template);
if (mt == null) return;
String content = MessageFormat.format(mt.getContent(), arg);
smsUtils.send(phone, content);
MessageLog log = new MessageLog();
log.setToUser(phone);
log.setContent(content);
log.setTemplate(template);
log.setType(mt.getType());
messageLogMapper.insert(log);
}
}
//package cn.com.glsx.notify.modules.service;
//
//import cn.com.glsx.admin.services.notifyservice.model.WechatTemplateMessageDTO;
//import com.glsx.plat.wechat.modules.service.WxPushService;
//import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
//import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//
///**
// * @author payu
// */
//@Service
//public class WeixinService {
//
// @Autowired
// private WxPushService wxPushService;
//
// public void push(String appid, WechatTemplateMessageDTO wtmm) {
// WxMpTemplateMessage wechatTemplate = new WxMpTemplateMessage();
// wechatTemplate.setTemplateId(wtmm.getTemplateId());
// wechatTemplate.setToUser(wtmm.getOpenid());
// wechatTemplate.setUrl(wtmm.getUrl());
//
// List<WxMpTemplateData> data = new ArrayList<>();
// for (Map.Entry<String, String> entry : wtmm.getData().entrySet()) {
// String key = entry.getKey();
// String value = entry.getValue();
// if (key.toLowerCase().contains("keyword")) {
// data.add(new WxMpTemplateData(key, value, "#173177"));
// } else {
// data.add(new WxMpTemplateData(key, value));
// }
// }
// wechatTemplate.setData(data);
// wxPushService.push(appid, wechatTemplate);
// }
//
//}
package cn.com.glsx.notify.modules.utils;
import com.alibaba.fastjson.JSONObject;
import com.glsx.plat.common.utils.HttpUtils;
import com.glsx.plat.sms.properties.SMSProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.TreeMap;
/**
* @author payu
*/
@Slf4j
@Component("smsUtils")
public class SmsUtils {
@Resource
private SMSProperties properties;
/**
* 短信
*
* @param phone
* @param content
*/
// @Async
public void send(String phone, String content) {
send(phone, content, properties.getSource());
}
/**
* 短信派单
*
* @param phone
* @param content
* @param source
*/
// @Async
public void send(String phone, String content, String source) {
TreeMap<String, Object> treeMap = new TreeMap<>();
treeMap.put("method", "glsx.message.sendmessage");
treeMap.put("format", "json");
treeMap.put("akey", properties.getAccessKeyId());
treeMap.put("v", "1.0.0");
treeMap.put("channel", "1001");
treeMap.put("lock", "2AC16F3AB37C129E273A4979FD0A46B0");
treeMap.put("source", source);
treeMap.put("type", "1");
treeMap.put("phone", phone);
treeMap.put("content", content);
treeMap.put("subcode", "");
log.info("Send Sms:" + treeMap.toString());
String url = properties.getUrl();
log.info("短信接口:" + url);
try {
String res = HttpUtils.get(url, treeMap);
log.info("Result:" + res);
if (StringUtils.isNotEmpty(res)) {
if (res.contains("<html>")) {
log.error("短信服务不可用,返回html...");
}
if (res.contains("{")) {
JSONObject jsonObject = JSONObject.parseObject(res);
String code = jsonObject.getString("code");
if (!"0".equals(code)) {
res = HttpUtils.get(url, treeMap);
log.info("Failure resend result:" + res);
}
}
} else {
log.error("短信服务不可用,返回为空");
}
} catch (IllegalStateException ex) {
if (StringUtils.isNotEmpty(url)) {
log.error("IllegalStateException", ex);
}
} catch (Exception ex) {
log.error("SendSmsException", ex);
try {
String res1 = HttpUtils.get(url, treeMap);
log.info("Exception resend result:" + res1);
} catch (Exception e) {
log.error("ReSendSmsException", ex);
}
}
}
// public static void main(String[] args) {
// SmsUtils util = new SmsUtils();
// util.send("18682185876", "您本次操作验证码为:{0},五分钟内有效。", "frms_sms_assign");
// }
}
package cn.com.glsx.notify.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@ChannelHandler.Sharable
public class MyByteEncoder extends MessageToByteEncoder<byte[]> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, byte[] bytes, ByteBuf out) throws Exception {
log.info("MyByteEncoder 被调用");
//字节数组
out.writeBytes(bytes);
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.modules.controller.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
public class NettyDataSvervice {
private static final ReentrantLock Lock = new ReentrantLock();
/**
* 将传送过来的数据进行解析,包括异或运算 (第一次服务器端给客户端发)
*
* @param receiveData
* @return
*/
public static String sendData(String receiveData) {
final ReentrantLock putLock = Lock;
log.info("接收数据" + receiveData);
putLock.lock();
try {
//此处需要读数据进行校验以及分包黏包处理,本文主要提供思路所以省略
/*
* 处理分包黏包、拆分、解析等
*/
//数据解析
parseData(receiveData);
try {
//数据帧WebSocket推送
WebSocketServer.BroadCastInfo(receiveData);
} catch (IOException e) {
e.printStackTrace();
}
return receiveData;
} finally {
putLock.unlock();
}
}
/**
* 数据入库处理
*/
public static void parseData(String receiveData) {
System.out.println("执行入库操作");
}
}
package cn.com.glsx.notify.netty;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyInitializer extends ChannelInitializer {
@Autowired
public MyByteEncoder myByteEncoder;
@Override
protected void initChannel(Channel channel) throws Exception {
//创建一个通道初始化对象(匿名对象)
//给pipeline 设置处理器
//可以使用一个集合管理 SocketChannel,再推送消息时,可以将业务加入到各个channel对应的NIOEventLoop的taskQueue
// 或者 scheduleTaskQueue
log.info("客户socketchannel hashcode=" + channel.hashCode());
//入站解码
//channel.pipeline().addLast(new MyByteToLongDecoder2());
//出站编码
channel.pipeline().addLast(new MyByteEncoder());
channel.pipeline().addLast(new NettyServerHandler());
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalTime;
import java.util.Objects;
@Slf4j
public class NettySendThread implements Runnable {
private ChannelHandlerContext ctx;
private String data;
public NettySendThread(ChannelHandlerContext ctx, String data) {
this.ctx = ctx;
this.data = data;
}
@Override
public void run() {
String bcc = NettyDataSvervice.sendData(data);
log.info("接收需要返回的消息:" + bcc);
if (Objects.isNull(bcc)) {
return;
}
//数据的发送与接收都是16进制
byte[] sendData = NettyByteAndStringUtils.hexToByte(bcc);
log.info("发送数据时间: " + LocalTime.now());
ctx.writeAndFlush(sendData);
}
}
package cn.com.glsx.notify.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@Configuration
public class NettyServer {
@Value("${netty.server.port}")
private Integer port;
final EventLoopGroup bossGroup = new NioEventLoopGroup();
final EventLoopGroup workerGroup = new NioEventLoopGroup();
public void run() throws Exception {
//创建BossGroup 和 WorkerGroup
//说明
//1. 创建两个线程组 bossGroup 和 workerGroup
//2. bossGroup 只是处理连接请求 , 真正的和客户端业务处理,会交给 workerGroup完成
//3. 两个都是无限循环
//4. bossGroup 和 workerGroup 含有的子线程(NioEventLoop)的个数
//默认实际 cpu核数 * 2
try {
//创建服务器端的启动对象,配置参数
ServerBootstrap bootstrap = new ServerBootstrap();
//使用链式编程来进行设置
//设置两个线程组
bootstrap.group(bossGroup, workerGroup)
//使用NioSocketChannel 作为服务器的通道实现
.channel(NioServerSocketChannel.class)
// 设置线程队列得到连接个数(也可以说是并发数)
.option(ChannelOption.SO_BACKLOG, 2048)
//设置保持活动连接状态
.childOption(ChannelOption.SO_KEEPALIVE, true)
//.handler(null) // 该 handler对应 bossGroup , childHandler 对应 workerGroup
//.childOption(ChannelOption.TCP_NODELAY,true)//socketchannel的设置,关闭延迟发送
.childHandler(new NettyInitializer());
log.info(".....服务器 is ready.....");
//绑定一个端口并且同步, 生成了一个 ChannelFuture 对象
//启动服务器(并绑定端口)
ChannelFuture cf = bootstrap.bind(port).sync();
//给cf 注册监听器,监控我们关心的事件
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (cf.isSuccess()) {
log.info("监听端口[{}]成功!", port);
} else {
log.error("监听端口[{}]失败!", port);
}
}
});
//对关闭通道进行监听
cf.channel().closeFuture().sync();
} catch (Exception e) {
log.error(" netty服务启动异常 " + e.getMessage());
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.netty;
import cn.com.glsx.notify.netty.utils.NettyByteAndStringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static Lock lock_1 = new ReentrantLock();
private static Lock lock_2 = new ReentrantLock();
private static Lock lock_3 = new ReentrantLock();
private static Lock lock_4 = new ReentrantLock();
/**
* 管理一个全局map,保存连接进服务端的通道数量
*/
private static final ConcurrentHashMap<ChannelId, ChannelHandlerContext> CHANNEL_MAP = new ConcurrentHashMap<>();
@Override //数据读取完毕
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//writeAndFlush 是 write + flush
//将数据写入到缓存,并刷新
//一般讲,我们对这个发送的数据进行编码
//ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(>^ω^<)喵1", CharsetUtil.UTF_8));
}
/**
* 处理异常, 一般是需要关闭通道
*
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
log.info("服务端异常关闭" + ctx.channel());
}
/**
* @param ctx
* @DESCRIPTION: 有客户端连接服务器会触发此函数
* @return: void
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
lock_1.lock();
try {
//获取连接通道唯一标识
ChannelId channelId = ctx.channel().id();
//如果map中不包含此连接,就保存连接
if (CHANNEL_MAP.containsKey(channelId)) {
log.info("客户端【" + channelId + "】是连接状态,连接通道数量: " + CHANNEL_MAP.size());
} else {
//保存连接
CHANNEL_MAP.put(channelId, ctx);
log.info("客户端【" + channelId + "】连接netty服务器");
log.info("连接通道数量: " + CHANNEL_MAP.size());
}
} finally {
lock_1.unlock();
}
}
/**
* @param ctx
* @DESCRIPTION: 有客户端终止连接服务器会触发此函数
* @return: void
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
lock_2.lock();
try {
ChannelId channelId = ctx.channel().id();
//包含此客户端才去删除
if (CHANNEL_MAP.containsKey(channelId)) {
//删除连接
CHANNEL_MAP.remove(channelId);
System.out.println();
log.info("客户端【" + channelId + "】退出netty服务器");
log.info("连接通道数量: " + CHANNEL_MAP.size());
}
} finally {
lock_2.unlock();
}
}
/**
* 1. ChannelHandlerContext ctx:上下文对象, 含有 管道pipeline , 通道channel, 地址
* 2. Object msg: 就是客户端发送的数据 默认Object
* <p>
* 读取数据实际(这里我们可以读取客户端发送的消息)
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
lock_3.lock();
try {
log.info("服务器读取线程 " + Thread.currentThread().getName() + " channle = " + ctx.channel());
Channel channel = ctx.channel();
//将 msg 转成一个 ByteBuf
//ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
ByteBuf buf = (ByteBuf) msg;
//得到此时客户端的数据长度
int bytes_length = buf.readableBytes();
//组件新的字节数组
byte[] buffer = new byte[bytes_length];
buf.readBytes(buffer);
final String allData = NettyByteAndStringUtils.byteToHex(buffer);
log.info("进入服务端数据:" + allData);
ctx.executor().execute(new NettySendThread(ctx, allData));
} finally {
lock_3.unlock();
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
lock_4.lock();
try {
String socketString = ctx.channel().remoteAddress().toString();
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) {
log.info("Client: " + socketString + " READER_IDLE 读超时");
ctx.disconnect();
} else if (event.state() == IdleState.WRITER_IDLE) {
log.info("Client: " + socketString + " WRITER_IDLE 写超时");
ctx.disconnect();
} else if (event.state() == IdleState.ALL_IDLE) {
log.info("Client: " + socketString + " ALL_IDLE 总超时");
ctx.disconnect();
}
}
} finally {
lock_4.unlock();
}
}
}
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.notify.netty.utils;
import java.util.concurrent.locks.ReentrantLock;
public class NettyByteAndStringUtils {
private final static ReentrantLock Lock = new ReentrantLock();
/**
* byte数组转hex
*/
public static String byteToHex(byte[] bytes) {
final ReentrantLock putLock = Lock;
putLock.lock();
try {
String strHex = "";
StringBuilder sb = new StringBuilder("");
for (byte aByte : bytes) {
strHex = Integer.toHexString(aByte & 0xFF);
// 每个字节由两个字符表示,位数不够,高位补0
sb.append((strHex.length() == 1) ? "0" + strHex : strHex);
}
return sb.toString().trim();
} finally {
putLock.unlock();
}
}
/**
* hex转byte数组
*/
public static byte[] hexToByte(String hex) {
final ReentrantLock putLock = Lock;
putLock.lock();
try {
int m = 0, n = 0;
// 每两个字符描述一个字节
int byteLen = hex.length() / 2;
byte[] ret = new byte[byteLen];
for (int i = 0; i < byteLen; i++) {
m = i * 2 + 1;
n = m + 1;
int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
ret[i] = (byte) intVal;
}
return ret;
} finally {
putLock.unlock();
}
}
/**
* 字节数组的大小
*/
public static int getByteSize(byte[] bytes) {
final ReentrantLock putLock = Lock;
putLock.lock();
try {
int size = 0;
if (bytes == null || bytes.length == 0) {
return 0;
}
for (byte aByte : bytes) {
if (aByte == '\0') {
break;
}
size++;
}
return size;
} finally {
putLock.unlock();
}
}
}
#项目名称
spring.application.name=glsx-ne-shield-notifycenter
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path=/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
#nacos配置中心
spring.cloud.nacos.config.server-addr=192.168.3.206:8848
#nacos配置id,完整dataId=${spring.cloud.nacos.config.prefix}-${spring.profiles.active}.${file-extension(由新增配置时选的文件类型决定)}
#示例:http://192.168.0.63:8848/nacos/v1/cs/configs?dataId=glsx-rest-admin.properties&group=DEV_GROUP
spring.cloud.nacos.config.group=NESHIELD_DEV_GROUP
#配置prefix,默认值同${spring.application.name}
spring.cloud.nacos.config.prefix=${spring.application.name}
#配置开发环境
spring.profiles.active=${profile.active}
#配置格式
spring.cloud.nacos.config.file-extension=properties
#微服务sentinel、zipkin、actuator等公共配置
spring.cloud.nacos.config.shared-configs[0].data-id=glsx-rest-microservice-share.properties
spring.cloud.nacos.config.shared-configs[0].group=DEV_GROUP
spring.cloud.nacos.config.shared-configs[0].refresh=true
#数据库、redis等公共配置
spring.cloud.nacos.config.shared-configs[1].group=NESHIELD_DEV_GROUP
spring.cloud.nacos.config.shared-configs[1].data-id=glsx-ne-shield-share-dev.properties
spring.cloud.nacos.config.shared-configs[1].refresh=true
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!--
说明:
1. 文件的命名和加载顺序有关
logback.xml早于application.yml加载,logback-spring.xml晚于application.yml加载
如果logback配置需要使用application.yml中的属性,需要命名为logback-spring.xml
2. logback使用application.yml中的属性
使用springProperty才可使用application.yml中的值 可以设置默认值
如果非要用yaml文件,那么只能使用绝对路径,例如:
logback-spring.xml引入文件:
<property file="${HOME}/configuration/application.yaml"/>
-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<property resource="bootstrap.properties"/>
<property name="APP_NAME" value="${spring.application.name}"/>
<!-- 生成日志文件目录 -->
<property name="LOG_FILE" value="${logging.path}"/>
<contextName>${APP_NAME}</contextName>
<turboFilter class="com.glsx.plat.common.loggin.BootTurboFilter">
<Marker>${APP_NAME}</Marker>
</turboFilter>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<!-- <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />-->
<!-- <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- 控制台打印日志 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志定时生成压缩文件 -->​
<appender name="flatfile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 日志进行格式化 -->
<!-- <appender name="logstash" class="ch.qos.logback.core.rolling.RollingFileAppender">-->
<!-- <file>${LOG_FILE}.json</file>-->
<!-- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">-->
<!-- <fileNamePattern>${LOG_FILE}.json.%d{yyyy-MM-dd}.gz</fileNamePattern>-->
<!-- <maxHistory>7</maxHistory>-->
<!-- </rollingPolicy>-->
<!-- <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">-->
<!-- <providers>-->
<!-- <timestamp>-->
<!-- <timeZone>UTC</timeZone>-->
<!-- </timestamp>-->
<!-- <pattern>-->
<!-- <pattern>-->
<!-- {-->
<!-- "severity": "%level",-->
<!-- "service": "${APP_NAME:-}",-->
<!-- "trace": "%X{X-B3-TraceId:-}",-->
<!-- "span": "%X{X-B3-SpanId:-}",-->
<!-- "parent": "%X{X-B3-ParentSpanId:-}",-->
<!-- "exportable": "%X{X-Span-Export:-}",-->
<!-- "pid": "${PID:-}",-->
<!-- "thread": "%thread",-->
<!-- "class": "%logger{40}",-->
<!-- "rest": "%message"-->
<!-- }-->
<!-- </pattern>-->
<!-- </pattern>-->
<!-- </providers>-->
<!-- </encoder>-->
<!-- </appender>-->
​
<root level="INFO">
<appender-ref ref="console"/>
<appender-ref ref="flatfile"/>
<!-- uncomment this to have also JSON logs -->
<!-- <appender-ref ref="logstash"/>-->
</root>
</configuration>
\ No newline at end of file \ No newline at end of file
<?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="cn.com.glsx.notify.modules.mapper.MessageLogMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.notify.modules.entity.MessageLog">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="from_user" jdbcType="VARCHAR" property="fromUser" />
<result column="to_user" jdbcType="VARCHAR" property="toUser" />
<result column="template" jdbcType="VARCHAR" property="template" />
<result column="subject" jdbcType="VARCHAR" property="subject" />
<result column="content" jdbcType="VARCHAR" property="content" />
<result column="attachment" jdbcType="VARCHAR" property="attachment" />
<result column="type" jdbcType="VARCHAR" property="type" />
<result column="del_flag" jdbcType="INTEGER" property="delFlag" />
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
<result column="created_by" jdbcType="INTEGER" property="createdBy" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
<result column="updated_by" jdbcType="INTEGER" property="updatedBy" />
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, from_user, to_user, `template`, subject, content, attachment, `type`,
del_flag, created_date, created_by, updated_date, updated_by
</sql>
</mapper>
\ No newline at end of file \ No newline at end of file
<?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="cn.com.glsx.notify.modules.mapper.MessageTemplateMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.notify.modules.entity.MessageTemplate">
<!--
WARNING - @mbg.generated
-->
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="template" jdbcType="VARCHAR" property="template"/>
<result column="subject" jdbcType="VARCHAR" property="subject"/>
<result column="content" jdbcType="VARCHAR" property="content"/>
<result column="type" jdbcType="VARCHAR" property="type"/>
<result column="del_flag" jdbcType="INTEGER" property="delFlag"/>
<result column="created_date" jdbcType="TIMESTAMP" property="createdDate"/>
<result column="created_by" jdbcType="INTEGER" property="createdBy"/>
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate"/>
<result column="updated_by" jdbcType="INTEGER" property="updatedBy"/>
</resultMap>
<sql id="Base_Column_List">
<!--
WARNING - @mbg.generated
-->
id, `template`, subject, content, `type`, del_flag, created_date,
created_by, updated_date, updated_by
</sql>
<select id="findByTemplate" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_message_template
where template = #{template}
</select>
<select id="findByTemplateAndType" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from t_message_template
where template = #{template}
and type = #{type}
</select>
</mapper>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.test;
import cn.com.glsx.Application;
import cn.com.glsx.admin.common.constant.Constants;
import cn.com.glsx.admin.services.notifyservice.model.PCTemplateMessageDTO;
import cn.com.glsx.admin.services.notifyservice.model.WechatTemplateMessageDTO;
import cn.com.glsx.notify.modules.service.MailService;
import cn.com.glsx.notify.modules.service.PCService;
import cn.com.glsx.notify.modules.service.SmsService;
import com.glsx.plat.common.utils.DateUtils;
import com.google.common.collect.Maps;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class NotifyApplicationTests {
@Autowired
private SmsService smsService;
@Autowired
private MailService mailService;
@Autowired
private PCService pcService;
// @Autowired
// private WeixinService weixinService;
@Test
public void testSms() {
Map<String, Object> args = new HashMap<>();
args.put("code", 1234);
smsService.sendSms("18682185876", "SMS_TEMPLATE_VERIFY_CODE", args.values());
}
@Test
public void testMail() throws Exception {
Map<String, Object> args = new HashMap<>();
args.put("arg1", "刘宇峰");
args.put("arg2", "B73493098765");
args.put("arg3", 1234);
//mailService.sendSimpleMail("levphon@vip.qq.com", "notifycenter test", "MAIL_TEMPLATE_ORDER_PAID_NOTIFY_OPERATOR", args.values());
List<Map<String, String>> filepaths = Lists.newArrayList();
Map<String, String> girl1 = Maps.newHashMap();
girl1.put("filename", "girl1.jpg");
girl1.put("filepath", "https://pic.netbian.com/uploads/allimg/220215/004859-1644857339de97.jpg");
filepaths.add(girl1);
mailService.sendAttachmentsMail("levphon@vip.qq.com", "notifycenter test" + DateUtils.format(new Date()), "MAIL_TEMPLATE_ORDER_PAID_NOTIFY_OPERATOR", filepaths);
Thread.sleep(30000);
}
@Test
public void testPC() {
PCTemplateMessageDTO templateMessageDTO = PCTemplateMessageDTO.builder()
.application(Constants.SERVER_NAME + "_TOPIC")
.from("alarmcenter")
.to("1")
.template("test")
.content("设备离线报警")
.type(1)
.build();
pcService.sendMessage(templateMessageDTO);
}
@Test
public void testWeixinSend() {
Map<String, String> data = new HashMap<>();
data.put("first", "您的趣融贷款账单已出," + DateUtils.formatNormal(new Date()) + "是您的趣融贷款还款日。");
data.put("keyword1", "1856.65" + "元");
data.put("keyword2", "第" + 5 + "期");
data.put("remark", "如有疑问,请联系客服,客服热线:400-8060-999");
WechatTemplateMessageDTO model = WechatTemplateMessageDTO.builder()
.templateId("nclNdUjGPpXgQQth55Cx2BoJQscWlcKkEy97uZ9MXK0")
.openid("oxAQwwMiYESDE8--YOopaAl6F4uo")
.url("http://www.baidu.com")
.data(data).build();
// weixinService.push("wxa9b785873a4b0793", model);
}
}
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!