初始化socket组件

dev_v1.0.1
liu 2 years ago
parent e46bbe9259
commit 5f283f24e4

@ -8,6 +8,7 @@ import cn.hutool.jwt.JWTUtil;
import com.supervision.domain.UserInfo;
import com.supervision.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@ -17,10 +18,12 @@ import javax.servlet.http.HttpServletResponse;
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//请求消息头获取用户ID
String token = request.getHeader("token");
// 如果是开发环境,不获取token
if (StrUtil.isBlank(token)) {
throw new BusinessException("当前用户未登录");
}

@ -1,5 +1,6 @@
package com.supervision.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ -28,6 +29,8 @@ public class WebConfig implements WebMvcConfigurer {
paths.add("/error");
paths.add("/favicon.ico");
paths.add("/user/login");
// 开发环境,放开不校验token.每次修改这里需要重启(热部署不行)
paths.add("/**");
return paths;
}
}

@ -6,10 +6,11 @@ import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.supervision.domain.UserInfo;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
public class TokenUtil {
public static String creatToken(UserInfo userInfo){
public static String creatToken(String userInfo){
final JWTSigner signer = JWTSignerUtil.hs256("123456".getBytes());
JSONObject info = JSONUtil.parseObj(userInfo);
// 过期时间一天

@ -30,6 +30,11 @@
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
</project>

@ -1,9 +1,14 @@
package com.supervision;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
@EnableWebSocket
@SpringBootApplication
@MapperScan(basePackages = {"com.supervision.**"})
public class VirtualPatientApplication {
public static void main(String[] args) {

@ -0,0 +1,26 @@
package com.supervision.controller;
import com.supervision.websocket.cache.WebSocketUserCache;
import io.swagger.annotations.Api;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import javax.annotation.Resource;
import java.io.IOException;
@Api(tags = "问诊")
@RestController
@RequestMapping("/ask/")
public class AskController {
@RequestMapping("/send")
public void sendMessage(String message,String id) throws IOException {
WebSocketSession session = WebSocketUserCache.getSession(id);
session.sendMessage(new TextMessage(message));
}
}

@ -1,26 +1,40 @@
package com.supervision.controller;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.supervision.domain.UserInfo;
import com.supervision.exception.BusinessException;
import com.supervision.model.User;
import com.supervision.service.UserService;
import com.supervision.util.TokenUtil;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@Api(tags = "用户管理")
@RestController
@RequestMapping("user")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping("login")
public String login(String userName, String password) {
if (StrUtil.isBlank(userName)) {
public String login(String userAccount, String password) {
if (!StrUtil.isAllNotBlank(userAccount, password)) {
throw new BusinessException("用户名不能为空");
}
// TODO 后面实现
UserInfo userInfo = new UserInfo();
return TokenUtil.creatToken(userInfo);
Optional<User> user = userService.lambdaQuery().eq(User::getAccount, userAccount).last("limit 1").oneOpt();
if (!user.isPresent()) {
throw new BusinessException("未找到用户");
}
if (!user.get().getPassword().equals(password)) {
throw new BusinessException("密码错误");
}
return TokenUtil.creatToken(JSONUtil.toJsonStr(user.get()));
}
}

@ -0,0 +1,38 @@
package com.supervision.websocket.cache;
import cn.hutool.core.util.ObjectUtil;
import com.supervision.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Slf4j
public class WebSocketUserCache {
private static final Map<String, WebSocketSession> map = new ConcurrentHashMap<>();
public static void login(String id, WebSocketSession socketSession) {
map.put(id, socketSession);
log.info("sessionId:{}注册成功", id);
}
public static void logout(String id) {
map.remove(id);
log.info("sessionId:{}注销成功", id);
}
public static WebSocketSession getSession(String id){
WebSocketSession webSocketSession = map.get(id);
if (ObjectUtil.isEmpty(webSocketSession)){
throw new BusinessException("未找到socket链接");
}
return webSocketSession;
}
}

@ -0,0 +1,24 @@
package com.supervision.websocket.config;
import com.supervision.websocket.handler.AskWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(askWebSocketHandler(), "/websocket")
.setAllowedOrigins("*");
}
@Bean
public WebSocketHandler askWebSocketHandler() {
return new AskWebSocketHandler();
}
}

@ -0,0 +1,33 @@
package com.supervision.websocket.handler;
import com.supervision.websocket.cache.WebSocketUserCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Slf4j
public class AskWebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 获取本次
String id = session.getId();
WebSocketUserCache.login(id, session);
// 连接建立时的处理逻辑
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理接收到的文本消息
log.info("收到消息:{}", message.toString());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 连接关闭时的处理逻辑
String id = session.getId();
WebSocketUserCache.logout(id);
}
}

@ -3,6 +3,8 @@ server:
port: 8899
spring:
profiles:
active: dev
application:
name: virtual-patient
##数据源配置
@ -10,9 +12,9 @@ spring:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.10.137:3306/doctor_training?useUnicode=true&characterEncoding=utf-8&useSSL=true&nullCatalogMeansCurrent=true&serverTimezone=GMT%2B8
url: jdbc:mysql://192.168.10.138:3306/virtual_patient?useUnicode=true&characterEncoding=utf-8&useSSL=true&nullCatalogMeansCurrent=true&serverTimezone=GMT%2B8
username: root
password: 'Root&&&123456'
password: '123456'
initial-size: 5 # 初始化大小
min-idle: 10 # 最小连接数
max-active: 20 # 最大连接数
@ -33,8 +35,7 @@ spring:
slow-sql-millis: 5000 # 慢 SQL 的标准,默认 3000单位毫秒
merge-sql: false # 合并多个连接池的监控数据默认false
profiles:
active: dev
mybatis-plus:
mapper-locations: classpath*:mapper/**/*.xml

Loading…
Cancel
Save