技术标签: 全栈技术贯通 spring boot java 工厂方法模式 策略模式 netty
上一章主要搭建了基础服务的使用,可以简单的进行通信,本章结合前端项目进行仿微信网页版开发,主要进行开发方案,数据库设计,代码部分讲解,前端vue项目使用,感谢网上的前端大佬开源的vue仿微信项目:GitHub - han960619/Vue-chat: 仿wechatPC版
体验地址:wechat
测试账户:18200891282/123456,18200891283/123456
小服务器速度不开,大家手下留情
效果图:
登录页面
聊天列表和单聊页面:
好友列表+搜索新好友
创建用户信息表:`chat_user_info ,创建用户id,手机号码索引
CREATE TABLE `chat_user_info` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '自增id',
`user_id` bigint NOT NULL COMMENT '用户id',
`nick_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '' COMMENT '昵称',
`phone` varchar(255) NOT NULL COMMENT '手机号码',
`img` varchar(512) NOT NULL COMMENT '头像',
`sex` bigint DEFAULT '0' COMMENT '性别 0:男 1:女',
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT '' COMMENT '地区',
`wx_number` varchar(50) NOT NULL COMMENT '自定义账号',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL COMMENT '更新时间',
`is_delete` bigint NOT NULL DEFAULT '0' COMMENT '是否删除 0:未删除,1:删除',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`) USING BTREE,
KEY `idx_user_phone` (`phone`) USING BTREE,
KEY `idx_user_wx_number` (`wx_number`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
大家可以自行去阿里云申请这个服务,一条短信也很便宜,不接入可以缓存写死验证码供使用
@Component
@Slf4j
public class MsmSendUtil {
@Resource
private RedisService redisService;
@Value("${aliyuncs.accessKeyId}")
private String accessKeyId;
@Value("${aliyuncs.secret}")
private String secret;
@Value("${aliyuncs.signName}")
private String signName;
@Value("${aliyuncs.templateCode}")
private String templateCode;
public boolean sendMsm(String phone) {
if (StringUtils.isEmpty(phone)) {
return false;
}
Object o = redisService.get(String.format(BaseConstant.MSM_PHONE_CODE_KEY, phone));
if(o!=null){
return true;
}
DefaultProfile profile =
DefaultProfile.getProfile("default", accessKeyId, secret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
Map<String, Object> param = new HashMap<>();
String code = RandomUtil.getFourBitRandom();
param.put("code", code);
request.putQueryParameter("PhoneNumbers", phone);
request.putQueryParameter("SignName", signName);
request.putQueryParameter("TemplateCode", templateCode);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
try {
CommonResponse response = client.getCommonResponse(request);
boolean success = response.getHttpResponse().isSuccess();
if(success){
redisService.set(String.format(BaseConstant.MSM_PHONE_CODE_KEY, phone),code,15*60);
}
return success;
} catch (Exception e) {
log.error("发送短信失败:手机号码:{}",phone,e);
}
return false;
}
基础的用户接口暂时这么多满足现有的场景,简单的逻辑就不详讲
目前系统没有细化权限,所以通过简单的uri规则进行鉴权
自定义全局filter类,实现GlobalFilter, Ordered,重写filter方法,根据uri判读权限和获取请求头的token校验登录态
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {
private AntPathMatcher antPathMatcher = new AntPathMatcher();
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String path = request.getURI().getPath();
log.info("请求路径为:{}",path);
List<String> tokenList = request.getHeaders().get(BaseConstant.HEADER_TOKEN_KEY);
if (antPathMatcher.match("/**/auth/**", path)) {
if (null == tokenList) {
ServerHttpResponse response = exchange.getResponse();
return out(response);
} else {
log.info("接口鉴权token为:{}",tokenList.get(0) );
if(!redisTemplate.hasKey(String.format(BaseConstant.USER_LOGIN_SUCCESS,tokenList.get(0)))){
ServerHttpResponse response = exchange.getResponse();
return out(response);
}
}
}
//内部服务接口,不允许外部访问
if (antPathMatcher.match("/**/inner/**", path)) {
ServerHttpResponse response = exchange.getResponse();
return out(response);
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
private Mono<Void> out(ServerHttpResponse response) {
JsonObject message = new JsonObject();
message.addProperty("success", false);
message.addProperty("code", ErrorMessage.TOKEN_IS_NOT_VALIDATE.getErrorCode());
message.addProperty("data", ErrorMessage.TOKEN_IS_NOT_VALIDATE.getMessage());
byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = response.bufferFactory().wrap(bits);
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
return response.writeWith(Mono.just(buffer));
}
}
自定义全局异常处理器,继承DefaultErrorWebExceptionHandler,重写getErrorAttributes方法,还需进行全局视图和Server配置该自定义异常处理器
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {
public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
ErrorProperties errorProperties, ApplicationContext applicationContext) {
super(errorAttributes, resourceProperties, errorProperties, applicationContext);
}
/**
* 获取异常属性
*/
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
Map<String, Object> map = new HashMap<>();
map.put("success", false);
map.put("code", 20005);
map.put("message", "系统异常,请稍后再试");
map.put("data", null);
return map;
}
/**
* 指定响应处理方法为JSON处理的方法
* @param errorAttributes
*/
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
/**
* 根据code获取对应的HttpStatus
* @param errorAttributes
* @return
*/
@Override
protected int getHttpStatus(Map<String, Object> errorAttributes) {
return 200;
}
}
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfig {
private final ServerProperties serverProperties;
private final ApplicationContext applicationContext;
private final ResourceProperties resourceProperties;
private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
public ErrorHandlerConfig(ServerProperties serverProperties,
ResourceProperties resourceProperties,
ObjectProvider<List<ViewResolver>> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer,
ApplicationContext applicationContext) {
this.serverProperties = serverProperties;
this.applicationContext = applicationContext;
this.resourceProperties = resourceProperties;
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(
errorAttributes,
this.resourceProperties,
this.serverProperties.getError(),
this.applicationContext);
exceptionHandler.setViewResolvers(this.viewResolvers);
exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
return exceptionHandler;
}
}
chat_friend:用户关系表
CREATE TABLE `chat_friend` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '自增id',
`biz_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '业务id',
`user_id` bigint NOT NULL COMMENT '用户id',
`friend_id` bigint NOT NULL COMMENT '好友id',
`is_top` bigint NOT NULL DEFAULT '0' COMMENT '是否置顶 0:否 1:是',
`not_receive_message` bigint NOT NULL DEFAULT '0' COMMENT '是否消息免打扰 0:否 1:是',
`remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '' COMMENT '好友备注',
`apply_reason` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT '' COMMENT '申请填写内容',
`is_pass` bigint NOT NULL DEFAULT '0' COMMENT '是否申请通过 0:否 1:是',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`is_delete` bigint NOT NULL DEFAULT '0' COMMENT '是否删除 0:否 1:是',
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`) USING BTREE,
KEY `idx_biz_id` (`biz_id`) USING BTREE,
KEY `idx_friend_id` (`friend_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
chat_list:用户聊天列表
CREATE TABLE `chat_list` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` bigint NOT NULL COMMENT '用户id',
`friend_id` bigint NOT NULL COMMENT '好友id',
`message_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT '' COMMENT '消息id',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`is_delete` bigint NOT NULL DEFAULT '0' COMMENT '是否删除 0:否 1:是',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
chat_message:用户消息信息表
CREATE TABLE `chat_message` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '自增id',
`message_id` varchar(64) NOT NULL COMMENT '消息id',
`message_type` bigint NOT NULL COMMENT '消息类型( 1:添加新好友 2:好友申请通过 3:获取聊天列表 4:获取历史聊天列表 5:单聊文本 6:群聊文本)',
`message_data` text COMMENT '消息内容(自定义json格式)',
`user_id` bigint NOT NULL COMMENT '发送用户userId',
`receive_id` bigint NOT NULL COMMENT '接收用户id 或者 群聊分组id',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL COMMENT '更新时间',
`is_delete` bigint NOT NULL DEFAULT '0' COMMENT '是否删除 0:未删除,1:删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=117 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
既然用到了websocket进行通信,所以有些数据就使用websocket进行交流。也为了划分服务的责任。
用户的好友关系采用api接口开发,关于实时的用户聊天数据例如用户发送聊天,动态聊天列表,新数据通知采用Websocket开发
上一章已经讲过用户连接websocket后如何绑定通道和多节点通信:
重点讲一下Webscoket和前端的通信流程:
定义固定的数据通信VO
@Data
public class NettyMessageVO {
/**
* 发送者id
* */
@JSONField(serializeUsing= ToStringSerializer.class)
private Long userId;
/**
* 接受者id
* */
@JSONField(serializeUsing= ToStringSerializer.class)
private Long receiveId;
/**
* 消息类型
* */
private Integer messageType;
/**
* 消息id
* */
private String messageId;
/**
* 消息内容
* */
private String data;
/**
* 消息类型为图片
* */
private String img;
/**
* 通道id
* */
private Object channelId;
private Integer pageNo;
private Integer pageSize;
private String nickName;
private String myImg;
}
策略模式+工厂模式使用:
AbstractHandle抽象处理器,包含抽象的handler处理类标识,处理方法
public interface AbstractHandle {
/**
* 获取类bean名
* */
String getServiceTypeName();
/**
* 具体业务处理
* */
Object handlerWebsocket(ChannelHandlerContext ctx,Object message) throws UnknownHostException;
}
HandlerServiceFactory处理器工厂类,服务初始化加载处理实现类到工厂类的map统一管理,根据实现类自定义map中的key实现类名
public class HandlerServiceFactory {
private static Map<String, AbstractHandle> serviceMap = new ConcurrentHashMap<String, AbstractHandle>();
public static AbstractHandle getHandlerService(String serviceName){
return serviceMap.get(serviceName);
}
public static void register(String serviceName,AbstractHandle abstractHandle){
Assert.notNull(serviceName,"实现类名不允许为空");
serviceMap.put(serviceName,abstractHandle);
}
}
具体实现操作实现AbstractHandle,InitializingBean:
SignleMessageHandlerImpl,通过getServiceTypeName()设置加载到map中的key名,通过实现InitializingBean下的afterPropertiesSet方法将类初始化到HandlerServiceFactory中
@Service
@Slf4j
public class SignleMessageHandlerImpl implements AbstractHandle, InitializingBean {
@Autowired
private ChatMessageService chatMessageService;
@Autowired
private SendMessage sendMessage;
@Override
public String getServiceTypeName() {
return HandlerServiceName.SINGLE_MESSAGE.getName();
}
@Override
public Object handlerWebsocket(ChannelHandlerContext ctx, Object message) throws UnknownHostException {
NettyMessageVO nettyMessageVO = (NettyMessageVO)message;
//新增消息记录
nettyMessageVO = chatMessageService.addNewMessage(nettyMessageVO);
sendMessage.send(ctx,nettyMessageVO,Boolean.FALSE);
return null;
}
@Override
public void afterPropertiesSet() throws Exception {
HandlerServiceFactory.register(getServiceTypeName(),this);
}
}
定义HandlerServiceName和NettyMessageType枚举来管理处理类名和对应前端请求处理的标识ytpe:
@Getter
public enum NettyMessageType {
ADD_FRIEND(1,"添加好友消息","add_friend"),
ADD_FRIEND_FISH(2,"好友申请成功","add_friend"),
CURRENT_FRIEND_CHAT_LIST(3,"获取好友聊天列表","current_cha_list"),
FRIEND_CHAT_MESSAGE(4,"获取历史聊天列表","friend_chat_message"),
SINGLE_MESSAGE(5,"单聊","single_message"),
ADD_CHAT_LIST(7,"聊天列表添加","add_chat_list"),
;
public Integer type;
public String message;
public String handleName;
NettyMessageType(Integer type,String message,String handleName){
this.type = type;
this.message = message;
this.handleName = handleName;
}
public static String getHandleNameByType(Integer type){
List<NettyMessageType> messageTypes = Arrays.asList(NettyMessageType.values());
NettyMessageType nettyMessageType = messageTypes.stream().filter(m -> m.getType().equals(type)).findFirst().get();
return nettyMessageType.getHandleName();
}
}
上述模式具体的使用:
HandlerServiceFactory.getHandlerService(NettyMessageType.getHandleNameByType(nettyMessageVO.getMessageType()))
.handlerWebsocket(null,nettyMessageVO);
netty服务集成springweb,提供api接口给其他服务进行实时消息推送
@RestController
@RequestMapping("/api/inner")
public class MessageAPI {
@PostMapping("/sendMessage")
public void sendMessage(@RequestBody NettyMessageVO nettyMessageVO) throws UnknownHostException {
HandlerServiceFactory.getHandlerService(NettyMessageType.getHandleNameByType(nettyMessageVO.getMessageType()))
.handlerWebsocket(null,nettyMessageVO);
}
}
最后websocket 的api编写处理也是使用mybatisplus来处理数据,最后返回数据到前端
spring:
application:
name: service-gateway
cloud:
nacos:
discovery:
server-addr:
config:
namespace: 85980dd0-86a2-4c67-80db-d13651592e4a
server-addr:
file-extension: yml
profiles:
active: dev
spring:
cloud:
nacos:
config:
ext-config[0]:
data-id: common.yml
refresh: false
这些就是本次更新的内容,利用自己空闲时间写写学学的小东西,这里面还有很多需要优化的地方,后续再补充完善,例如:
1.性能问题,有些表设计的不够合理,选择其他的数据库,毕竟聊天信息是海量的。
2.系统高可用问题
3.系统安全需要做信息加密传输
欢迎大家沟通交流,感谢这个vue仿微信的前端大佬,本人的前端很水
目录
文章浏览阅读645次。这个肯定是末尾的IDAT了,因为IDAT必须要满了才会开始一下个IDAT,这个明显就是末尾的IDAT了。,对应下面的create_head()代码。,对应下面的create_tail()代码。不要考虑爆破,我已经试了一下,太多情况了。题目来源:UNCTF。_攻防世界困难模式攻略图文
文章浏览阅读2.9k次,点赞3次,收藏10次。偶尔会用到,记录、分享。1. 数据库导出1.1 切换到dmdba用户su - dmdba1.2 进入达梦数据库安装路径的bin目录,执行导库操作 导出语句:./dexp cwy_init/[email protected]:5236 file=cwy_init.dmp log=cwy_init_exp.log 注释: cwy_init/init_123..._达梦数据库导入导出
文章浏览阅读1.9k次。1. 在官网上下载KindEditor文件,可以删掉不需要要到的jsp,asp,asp.net和php文件夹。接着把文件夹放到项目文件目录下。2. 修改html文件,在页面引入js文件:<script type="text/javascript" src="./kindeditor/kindeditor-all.js"></script><script type="text/javascript" src="./kindeditor/lang/zh-CN.js"_kindeditor.js
文章浏览阅读2.3k次,点赞6次,收藏14次。SPI的详情简介不必赘述。假设我们通过SPI发送0xAA,我们的数据线就会变为10101010,通过修改不同的内容,即可修改SPI中0和1的持续时间。比如0xF0即为前半周期为高电平,后半周期为低电平的状态。在SPI的通信模式中,CPHA配置会影响该实验,下图展示了不同采样位置的SPI时序图[1]。CPOL = 0,CPHA = 1:CLK空闲状态 = 低电平,数据在下降沿采样,并在上升沿移出CPOL = 0,CPHA = 0:CLK空闲状态 = 低电平,数据在上升沿采样,并在下降沿移出。_stm32g431cbu6
文章浏览阅读1.2k次,点赞2次,收藏8次。数据链路层习题自测问题1.数据链路(即逻辑链路)与链路(即物理链路)有何区别?“电路接通了”与”数据链路接通了”的区别何在?2.数据链路层中的链路控制包括哪些功能?试讨论数据链路层做成可靠的链路层有哪些优点和缺点。3.网络适配器的作用是什么?网络适配器工作在哪一层?4.数据链路层的三个基本问题(帧定界、透明传输和差错检测)为什么都必须加以解决?5.如果在数据链路层不进行帧定界,会发生什么问题?6.PPP协议的主要特点是什么?为什么PPP不使用帧的编号?PPP适用于什么情况?为什么PPP协议不_接收方收到链路层数据后,使用crc检验后,余数为0,说明链路层的传输时可靠传输
文章浏览阅读587次。软件测试工程师移民加拿大 无证移民,未受过软件工程师的教育(第1部分) (Undocumented Immigrant With No Education to Software Engineer(Part 1))Before I start, I want you to please bear with me on the way I write, I have very little gen...
文章浏览阅读304次。Thinkpad X250笔记本电脑,装的是FreeBSD,进入BIOS修改虚拟化配置(其后可能是误设置了安全开机),保存退出后系统无法启动,显示:secure boot failed ,把自己惊出一身冷汗,因为这台笔记本刚好还没开始做备份.....根据错误提示,到bios里面去找相关配置,在Security里面找到了Secure Boot选项,发现果然被设置为Enabled,将其修改为Disabled ,再开机,终于正常启动了。_安装完系统提示secureboot failure
文章浏览阅读10w+次,点赞93次,收藏352次。1、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。其它:strtok函数线程不安全,可以使用strtok_r替代。示例://借助strtok实现split#include <string.h>#include <stdio.h&_c++ 字符串分割
文章浏览阅读2.3k次。1 .高斯日记 大数学家高斯有个好习惯:无论如何都要记日记。他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?高斯出生于:1777年4月30日。在高斯发现的一个重要定理的日记_2013年第四届c a组蓝桥杯省赛真题解答
文章浏览阅读851次,点赞17次,收藏22次。摘要:本文利用供需算法对核极限学习机(KELM)进行优化,并用于分类。
文章浏览阅读1.1k次。一、系统弱密码登录1、在kali上执行命令行telnet 192.168.26.1292、Login和password都输入msfadmin3、登录成功,进入系统4、测试如下:二、MySQL弱密码登录:1、在kali上执行mysql –h 192.168.26.129 –u root2、登录成功,进入MySQL系统3、测试效果:三、PostgreSQL弱密码登录1、在Kali上执行psql -h 192.168.26.129 –U post..._metasploitable2怎么进入
文章浏览阅读257次。本文将为初学者提供Python学习的详细指南,从Python的历史、基础语法和数据类型到面向对象编程、模块和库的使用。通过本文,您将能够掌握Python编程的核心概念,为今后的编程学习和实践打下坚实基础。_python人工智能开发从入门到精通pdf