接口文档与 WebSocket
# 一、Knife4j / Swagger 接口文档
后端集成了 Swagger2 与增强 UI Knife4j,配置类位于 eladmin-common 模块的 vip.eladmin.config.webConfig.SwaggerConfig:
- 访问地址:本地启动后端后打开
http://localhost:8000/doc.html(或通过后台菜单「系统工具 → 接口文档」内嵌查看); - 环境开关:由
swagger.enabled控制(开发环境true,生产环境建议保持false); - 自动鉴权适配:
SwaggerConfig会扫描@AnonymousAccess放行接口,其余受保护接口自动关联Authorization请求头定义。
# 1. 在 Controller 与实体中编写文档注解
@RestController
@RequiredArgsConstructor
@Api(tags = "系统:岗位管理")
@RequestMapping("/api/job")
public class JobController {
@ApiOperation("查询岗位")
@GetMapping
@PreAuthorize("@el.check('job:list')")
public ResponseEntity<PageResult<JobDto>> queryJob(JobQueryCriteria criteria, Pageable pageable) {
return new ResponseEntity<>(jobService.queryAll(criteria, pageable), HttpStatus.OK);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
实体/DTO 字段通过 @ApiModelProperty 标注中文说明,不希望出现在请求体文档中的内部审计字段可加上 hidden = true:
@ApiModelProperty(value = "岗位名称", required = true)
private String name;
@ApiModelProperty(value = "创建时间", hidden = true)
private Timestamp createTime;
1
2
3
4
5
2
3
4
5
# 2. 在 Knife4j 中携带 Token 调试
- 先调用
POST /auth/login(或从浏览器前端请求头复制)获取完整的Bearer <token>; - 打开 Knife4j 左侧菜单 文档管理 → 全局参数设置,新增一个
header参数:参数名填Authorization,参数值填Bearer <你的token>; - 之后调试所有受保护接口都会自动带上认证头。
# 二、WebSocket 实时推送
后端在 eladmin-common 中通过 WebSocketConfig 注册了 ServerEndpointExporter,并在 eladmin-system 模块的 vip.eladmin.modules.maint.websocket.WebSocketServer 中提供了现成的服务端推送端点(目前用于「运维管理」实时推送应用部署日志与状态)。
# 1. 端点与消息模型
- 连接路径:
@ServerEndpoint("/webSocket/{sid}"),其中sid用于区分客户端或业务通道(如deploy、当前用户 ID 等); - 消息对象(
SocketMsg):包含msg(文本内容)与msgType(枚举MsgType:CONNECT/CLOSE/INFO/ERROR)。
# 2. 后端主动推送消息
在任意业务 Service 或异步任务中调用静态方法 WebSocketServer.sendInfo(...):
import vip.eladmin.modules.maint.websocket.MsgType;
import vip.eladmin.modules.maint.websocket.SocketMsg;
import vip.eladmin.modules.maint.websocket.WebSocketServer;
// 推送给指定 sid 客户端(sid 传 null 时向所有已连接客户端广播)
WebSocketServer.sendInfo(new SocketMsg("任务执行完成,共处理 120 条记录", MsgType.INFO), sid);
1
2
3
4
5
6
2
3
4
5
6
# 3. 前端建立连接示例
前端环境变量 .env.development / .env.production 已预置 VUE_APP_WS_API(HTTP 对应 ws://,HTTPS 对应 wss://):
const sid = 'biz-task-1'
const wsUrl = `${process.env.VUE_APP_WS_API}/webSocket/${sid}`
const ws = new WebSocket(wsUrl)
ws.onmessage = event => {
const data = JSON.parse(event.data) // { msg: '...', msgType: 'INFO' }
console.log(data.msgType, data.msg)
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
生产部署与安全注意
- 通过 Nginx 反向代理 WebSocket 时,需在对应
location /webSocket中配置proxy_http_version 1.1;、Upgrade与Connection "upgrade"头; - 当前内置
WebSocketServer默认用于运维日志流,若用于推送敏感业务数据,建议在@OnOpen中增加 Token 鉴权校验,且集群多节点场景需配合 Redis Pub/Sub 或 MQ 做跨节点消息广播。
帮助我们改善此页面! (opens new window)