前端代码:https://github.com/wyj41/yygh_html.git
后端代码:https://github.com/wyj41/yygh_parent.git
医院管理
目前我们把医院、科室和排班都上传到了平台,那么管理平台就应该把他们管理起来,在我们的管理平台能够直观的查看这些信息。
1.注册中心与服务调用
目前在医院列表中需要医院的信息和等级信息,而两段信息属于不同的的模块,service-hosp和service-cmn,所以我们需要使用到远程调用。
1.1 Nacos概述
Nacos 是阿里巴巴推出来的一个新开源项目,这是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。
Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。
Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施
1.2 常见的注册中心
- Eureka(原生,2.0遇到瓶颈,停止维护)
- Zookeeper(支持,专业的独立产品。例如:dubbo)
- Consul(原生,GO语言开发)
- Nacos
相对于 Spring Cloud Eureka 来说,Nacos 更强大。
Nacos = Spring Cloud Eureka + Spring Cloud Config
Nacos 可以与 Spring, Spring Boot, Spring Cloud 集成,并能代替 Spring Cloud Eureka, Spring Cloud Config。
- 通过 Nacos Server 和 spring-cloud-starter-alibaba-nacos-config 实现配置的动态变更。
- 通过 Nacos Server 和 spring-cloud-starter-alibaba-nacos-discovery 实现服务的注册与发现。
1.3 Nacos下载和安装
下载地址:https://github.com/alibaba/nacos/releases
下载版本:nacos-server-1.1.4.tar.gz或nacos-server-1.1.4.zip,解压任意目录即可
(链接:https://pan.baidu.com/s/1j7-A8LfUxR6lHAbGirC5Uw 提取码:wbjo)
启动Nacos服务
Linux/Unix/Mac
启动命令(standalone代表着单机模式运行,非集群模式)
启动命令:sh startup.sh -m standalone
Windows
启动命令:cmd startup.cmd 或者双击startup.cmd运行文件。
访问:http://localhost:8848/nacos
用户名密码:nacos/nacos
1.4 注册服务
1.在service模块pom文件引入依赖
<!-- 服务注册 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2.在配置文件添加nacos服务地址
分别在service_hosp和service_cmn的配置文件application.yml中添加
spring:
cloud:
nacos:
server-addr: 127.0.0.1:8848
注:记得检查下面内容(在nacos中显示该名称)
spring:
application:
name: service-hosp
3.分别在service_hosp和service_cmn启动类中添加注解
@SpringBootApplication
@ComponentScan(basePackages = "com.atguigu")
@EnableDiscoveryClient
public class ServiceHospApplication {
...
}
4.启动service_hosp和service_cmn服务,在Nacos管理界面的服务列表中可以看到注册的服务
在“服务管理” ==> “服务列表中查看”
2.医院列表
2.1 医院列表api接口
添加service分页接口与实现
在HospitalService类添加分页接口
//医院列表(条件查询分页)
Page<Hospital> selectHospitalPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo);
HospitalServiceImpl类实现分页
//医院列表(条件查询分页)
@Override
public Page<Hospital> selectHospitalPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
//创建pageable对象
Pageable pageable = PageRequest.of(page-1,limit);
//创建条件匹配器
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase(true);
//hospitalQueryVo转换Hospital对象
Hospital hospital = new Hospital();
BeanUtils.copyProperties(hospitalQueryVo,hospital);
//创建对象
Example<Hospital> example = Example.of(hospital,matcher);
//调用方法实现查询
Page<Hospital> all = hospitalRepository.findAll(example,pageable);
return all;
}
添加controller方法
添加com.myproject.yygh.hosp.controller.HospitalController类
package com.myproject.yygh.hosp.controller;
import com.myproject.yygh.common.result.Result;
import com.myproject.yygh.hosp.service.HospitalService;
import com.myproject.yygh.model.hosp.Hospital;
import com.myproject.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/admin/hosp/hospital")
@CrossOrigin
public class HospitalController {
@Autowired
private HospitalService hospitalService;
//医院列表(条件查询分页)
@GetMapping("list/{page}/{limit}")
public Result listHosp(@PathVariable Integer page,
@PathVariable Integer limit,
HospitalQueryVo hospitalQueryVo){
Page<Hospital> pageModel = hospitalService.selectHospitalPage(page,limit,hospitalQueryVo);
return Result.ok(pageModel);
}
}
2.2 service-cmn模块提供接口
由于我们的医院等级、省市区地址都是取的数据字典value值,因此我们在列表显示医院等级与医院地址时要根据数据字典value值获取数据字典名称
通过学习数据字典我们知道,根据上级编码与value值可以获取对应的数据字典名称,如果value值能够保持唯一(不一定唯一),我们也可以直接通过value值获取数据字典名称,目前省市区三级数据我们使用的是国家统计局的数据,数据编码我们就是数据字典的id与value,所以value能够唯一确定一条数据字典。
添加service接口与实现
在DictService类添加接口
//根据dictCode和value查询
String getDictName(String dictCode, String value);
DictServiceImpl类实现
//根据dictCode和value查询
@Override
public String getDictName(String dictCode, String value) {
//如果dictCode为空,直接根据value查询
if(StringUtils.isEmpty(dictCode)){
//直接根据value查询
QueryWrapper<Dict> wrapper = new QueryWrapper<>();
wrapper.eq("value",value);
Dict dict = baseMapper.selectOne(wrapper);
return dict.getName();
}else{
//如果dictCode非空,根据dictCode和value查询
//根据dictcode查询dict对象,得到dict的id值
QueryWrapper<Dict> wrapper = new QueryWrapper<>();
wrapper.eq("dict_code",dictCode);
Dict codeDict = baseMapper.selectOne(wrapper);
Long parent_id = codeDict.getId();
Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
.eq("parent_id",parent_id)
.eq("value",value));
return finalDict.getName();
}
}
添加controller方法
DictController类添加方法
//根据dictCode和value查询
@GetMapping("getName/{dictCode}/{value}")
public String getName(@PathVariable String dictCode,
@PathVariable String value){
String dictName = dictService.getDictName(dictCode,value);
return dictName;
}
//根据value查询
@GetMapping("getName/{value}")
public String getName(@PathVariable String value){
String dictName = dictService.getDictName("",value);
return dictName;
}
说明:提供两个api接口,如省市区不需要上级编码,医院等级需要上级编码
2.3 封装Feign服务调用
2.3.1 搭建service-client父模块
在yygh_parent下创建service_client模块,删除src包
修改pom文件
<?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>yygh_parent</artifactId>
<groupId>com.myproject</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<artifactId>service_client</artifactId>
<dependencies>
<dependency>
<groupId>com.myproject</groupId>
<artifactId>common_util</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.myproject</groupId>
<artifactId>model</artifactId>
<version>1.0</version>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided </scope>
</dependency>
<!-- 服务调用feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<scope>provided </scope>
</dependency>
</dependencies>
</project>
2.3.2 搭建service-cmn-client模块
在service_client模块下创建service_cmn_client模块
修改pom.xml文件
<?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>yygh_parent</artifactId>
<groupId>com.myproject</groupId>
<version>1.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service_cmn_client</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-core</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
添加Feign接口类
package com.myproject.yygh.cmn.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient("service-cmn")
@Repository
public interface DictFeignClient {
//根据dictCode和value查询
@GetMapping("/admin/cmn/dict/getName/{dictCode}/{value}")
public String getName(@PathVariable("dictCode") String dictCode,
@PathVariable("value") String value);
//根据value查询
@GetMapping("/admin/cmn/dict/getName/{value}")
public String getName(@PathVariable("value") String value);
}
2.4 医院接口远程调用数据字典
在service的pom.xml文件中添加依赖
<!-- 服务调用feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在ServiceHospApplication启动类中添加注解
@EnableFeignClients(basePackages = "com.myproject")
在service-hosp中导入依赖
<dependency>
<groupId>com.myproject</groupId>
<artifactId>service_cmn_client</artifactId>
<version>1.0</version>
</dependency>
调整service方法
修改HospitalServiceImpl类实现分页
@Autowired
private DictFeignClient dictFeignClient;
//医院列表(条件查询分页)
@Override
public Page<Hospital> selectHospitalPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
//创建pageable对象
Pageable pageable = PageRequest.of(page-1,limit);
//创建条件匹配器
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase(true);
//hospitalQueryVo转换Hospital对象
Hospital hospital = new Hospital();
BeanUtils.copyProperties(hospitalQueryVo,hospital);
//创建对象
Example<Hospital> example = Example.of(hospital,matcher);
//调用方法实现查询
Page<Hospital> all = hospitalRepository.findAll(example,pageable);
//获取查询list集合,遍历进行医院等级封装
all.getContent().stream().forEach(item -> {
this.setHospitalHosType(item);
});
return all;
}
//医院等级封装
private Hospital setHospitalHosType(Hospital hospital) {
//根据dictCode和value获取医院等级名称
String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
//查询省 市 地区
String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
String cityString = dictFeignClient.getName(hospital.getCityCode());
String districtString = dictFeignClient.getName(hospital.getDistrictCode());
hospital.getParam().put("hostypeString",hostypeString);
hospital.getParam().put("fullAddress",provinceString + cityString + districtString);
return hospital;
}
在swagger中测试
http://localhost:8201/swagger-ui.html
2.5 添加查询子节点接口
根据dicode查询下层节点
编写service
DictService
//根据dictCode获取下级节点
List<Dict> findByDictCode(String dictCode);
DictServiceImpl
//根据dictCode获取下级节点
@Override
public List<Dict> findByDictCode(String dictCode) {
//根据dictCode获取对应id
Dict codeDict = baseMapper.selectOne(new QueryWrapper<Dict>()
.eq("dict_code",dictCode));
//根据id获取子节点
List<Dict> childData = this.findChildData(codeDict.getId());
return childData;
}
编写controller
DictController中添加
//根据dictCode获取下级节点
@ApiOperation(value = "根据dictCode获取下级节点")
@GetMapping("findByDictCode/{dictCode}")
public Result findByDictCode(@PathVariable String dictCode){
List<Dict> list = dictService.findByDictCode(dictCode);
return Result.ok(list);
}
测试接口
http://localhost:8202/swagger-ui.html
传入dictCode为:Province
查看是否能够获取所有省的信息
2.5 医院列表前端
2.5.1 添加路由
在src/router/index.js 文件添加路由
添加在“编辑医院设置”的下面
{
path: 'hosp/list',
name: '医院列表',
component: () => import('@/views/hosp/list'),
meta: {
title: '医院列表', icon: 'table' }
}
2.5.2 封装api请求
创建/api/hosp.js
import request from '@/utils/request'
export default {
//医院列表
getHospList(page,limit,searchObj){
return request({
url:`/admin/hosp/hospital/list/${
page}/${
limit}`,
method:'get',
params:searchObj
})
},
//根据dictCode查询所有子节点(所有省)
findByDictCode(dictCode){
return request({
url:`/admin/cmn/dict/findByDictCode/${
dictCode}`,
method:'get'
})
},
//根据id查询子数据列表
findChildById(id){
return request({
url:`/admin/cmn/dict/findChildData/${
id}`,
method:'get'
})
}
}
2.5.3 添加组件
创建/views/hosp/list.vue组件
<template>
<div class="app-container">
<el-form :inline="true" class="demo-form-inline">
<el-form-item>
<el-select
v-model="searchObj.provinceCode"
placeholder="请选择省"
@change="provinceChanged">
<el-option
v-for="item in provinceList"
:key="item.id"
:label="item.name"
:value="item.id"/>
</el-select>
</el-form-item>
<el-form-item>
<el-select
v-model="searchObj.cityCode"
placeholder="请选择市"
@change="cityChanged">
<el-option
v-for="item in cityList"
:key="item.id"
:label="item.name"
:value="item.id"/>
</el-select>
</el-form-item>
<el-form-item>
<el-input v-model="searchObj.hosname" placeholder="医院名称"/>
</el-form-item>
<el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
<el-button type="default" @click="resetData()">清空</el-button>
</el-form>
<!-- banner列表 -->
<el-table v-loading="listLoading" :data="list"
border
fit
highlight-current-row>
<el-table-column
label="序号"
width="60"
align="center">
<template slot-scope="scope">
{
{ (page - 1) * limit + scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column label="医院logo">
<template slot-scope="scope">
<img :src="'data:image/jpeg;base64,'+scope.row.logoData" width="80">
</template>
</el-table-column>
<el-table-column prop="hosname" label="医院名称"/>
<el-table-column prop="param.hostypeString" label="等级" width="90"/>
<el-table-column prop="param.fullAddress" label="详情地址"/>
<el-table-column label="状态" width="80">
<template slot-scope="scope">
{
{ scope.row.status === 0 ? '未上线' : '已上线' }}
</template>
</el-table-column>
<el-table-column prop="createTime" label="创建时间"/>
<el-table-column label="操作" width="230" align="center">
</el-table-column>
</el-table>
<!-- 分页组件 -->
<el-pagination
:current-page="page"
:total="total"
:page-size="limit"
:page-sizes="[5, 10, 20, 30, 40, 50, 100]"
style="padding: 30px 0; text-align: center;"
layout="sizes, prev, pager, next, jumper, ->, total, slot"
@current-change="fetchData"
@size-change="changeSize"
/>
</div>
</template>
<script>
import hospApi from '@/api/hosp'
export default {
data(){
return {
listLoading: true, // 数据是否正在加载
list: null, // banner列表
total: 0, // 数据库中的总记录数
page: 1, // 默认页码
limit: 10, // 每页记录数
searchObj: {}, // 查询表单对象
provinceList: [], // 所有省集合
cityList: [], // 所有市集合
districtList: [] // 所有地区集合
}
},
created() {
//调用医院列表方法
this.fetchData(1)
//调用查询所有省的方法
this.findAllProvince()
},
methods: {
//医院列表
fetchData(page = 1){
this.page = page
hospApi.getHospList(this.page,this.limit,this.searchObj)
.then(response => {
//每页数据集合
this.list = response.data.content
//总记录数
this.total = response.data.totalElements
//加载图标不显示
this.listLoading = false
})
},
//查询所有省
findAllProvince(){
hospApi.findByDictCode('Province')
.then(response => {
this.provinceList = response.data
})
},
//点击某个省,显示里面市(联动)
provinceChanged(){
//初始化值
this.cityList = []
this.searchObj.cityCode = null;
//调用方法,根据省id,查询下面节点
hospApi.findChildById(this.searchObj.provinceCode)
.then(response => {
this.cityList = response.data
})
},
//分页,页码变化
changeSize(size){
this.limit = size
this.fetchData(1)
}
}
}
</script>
启动服务,查看功能
http://localhost:9528/
3.更新医院上线状态
3.1 Api接口
添加service接口
在HospitalService类添加接口
//更新医院的上线状态
void updateStatus(String id, Integer status);
HospitalServiceImpl类实现
//更新医院的上线状态
@Override
public void updateStatus(String id, Integer status) {
//根据id查询医院信息
Hospital hospital = hospitalRepository.findById(id).get();
//设置修改的值
hospital.setStatus(status);
hospital.setUpdateTime(new Date());
hospitalRepository.save(hospital);
}
添加controller方法
在HospitalController类添加方法
//更新医院的上线状态
@ApiOperation(value = "更新医院上线状态")
@GetMapping("updateHospStatus/{id}/{status}")
public Result updateHospStatus(@PathVariable String id,
@PathVariable Integer status){
hospitalService.updateStatus(id,status);
return Result.ok();
}
3.2 更新上线状态前端
封装api请求
在/api/hosp.js文件添加方法
//更新医院的上线状态
updateStatus(id,status){
return request({
url:`/admin/hosp/hospital/updateHospStatus/${
id}/${
status}`,
method:'get'
})
}
修改组件
修改/views/hosp/list.vue组件
在页面组件的“操作”中添加按钮
<el-table-column label="操作" width="230" align="center">
<template slot-scope="scope">
<el-button v-if="scope.row.status == 1" type="primary" size="mini" @click="updateStatus(scope.row.id, 0)">下线</el-button>
<el-button v-if="scope.row.status == 0" type="danger" size="mini" @click="updateStatus(scope.row.id, 1)">上线</el-button>
</template>
</el-table-column>
在脚本组件中添加方法
//更新医院的上线状态
updateStatus(id,status){
hospApi.updateStatus(id,status)
.then(response => {
//刷新页面
this.fetchData(1)
})
},
测试上线下线功能
4.医院详情
4.1 api接口
添加service接口
在HospitalService类添加接口
//医院详情信息
Map<String,Object> getHospById(String id);
HospitalServiceImpl类实现
//医院详情信息
@Override
public Map<String,Object> getHospById(String id) {
Map<String,Object> result = new HashMap<>();
Hospital hospital = this.setHospitalHosType(hospitalRepository.findById(id).get());
result.put("hospital",hospital);
//单独处理更直观
result.put("bookingRule",hospital.getBookingRule());
//不需要重复返回
hospital.setBookingRule(null);
return result;
}
添加controller方法
在HospitalController类添加方法
//医院详情信息
@ApiOperation(value = "医院详情信息")
@GetMapping("showHospDetail/{id}")
public Result showHospDetail(@PathVariable String id){
Map<String,Object> map = hospitalService.getHospById(id);
return Result.ok(map);
}
4.2 医院详情前端
添加隐藏路由
添加在“医院列表”下面
{
path: 'hospital/show/:id',
name: '查看',
component: () => import('@/views/hosp/show'),
meta: {
title: '查看', noicon: true },
hidden:true
}
修改医院列表组件
添加“查看”按钮
<el-table-column label="操作" width="230" align="center">
<template slot-scope="scope">
<router-link :to="'/hospSet/hospital/show/'+scope.row.id">
<el-button type="primary" size="mini">查看</el-button>
</router-link>
<el-button v-if="scope.row.status == 1" type="primary" size="mini" @click="updateStatus(scope.row.id, 0)">下线</el-button>
<el-button v-if="scope.row.status == 0" type="danger" size="mini" @click="updateStatus(scope.row.id, 1)">上线</el-button>
</template>
</el-table-column>
封装api请求
//查看医院详情
getHospById(id){
return request({
url:`/admin/hosp/hospital/showHospDetail/${
id}`,
method:'get'
})
}
添加显示页面组件
添加/views/hosp/show.vue组件
<template>
<div class="app-container" v-if="hospital!=null">
<h4>基本信息</h4>
<table class="table table-striped table-condenseda table-bordered" width="100%">
<tbody>
<tr>
<th width="15%">医院名称</th>
<td width="35%"><b style="font-size: 14px">{
{ hospital.hosname }}</b> | {
{ hospital.param.hostypeString }}</td>
<th width="15%">医院logo</th>
<td width="35%">
<img :src="'data:image/jpeg;base64,'+hospital.logoData" width="80">
</td>
</tr>
<tr>
<th>医院编码</th>
<td>{
{ hospital.hoscode }}</td>
<th>地址</th>
<td>{
{ hospital.param.fullAddress }}</td>
</tr>
<tr>
<th>坐车路线</th>
<td colspan="3">{
{ hospital.route }}</td>
</tr>
<tr>
<th>医院简介</th>
<td colspan="3">{
{ hospital.intro }}</td>
</tr>
</tbody>
</table>
<h4>预约规则信息</h4>
<table class="table table-striped table-condenseda table-bordered" width="100%">
<tbody>
<tr>
<th width="15%">预约周期</th>
<td width="35%">{
{ bookingRule.cycle }}天</td>
<th width="15%">放号时间</th>
<td width="35%">{
{ bookingRule.releaseTime }}</td>
</tr>
<tr>
<th>停挂时间</th>
<td>{
{ bookingRule.stopTime }}</td>
<th>退号时间</th>
<td>{
{ bookingRule.quitDay == -1 ? '就诊前一工作日' : '就诊当日' }}{
{ bookingRule.quitTime }} 前取消</td>
</tr>
<tr>
<th>预约规则</th>
<td colspan="3">
<ol>
<li v-for="item in bookingRule.rule" :key="item">{
{ item }}</li>
</ol>
</td>
</tr>
<br>
<el-row>
<el-button @click="back">返回</el-button>
</el-row>
</tbody>
</table>
</div>
</template>
<script>
import hospApi from '@/api/hosp'
export default {
data(){
return {
hospital:null, //医院信息
bookingRule:null //预约信息
}
},
created() {
//获取路由id
const id = this.$route.params.id
//调用方法,根据id查询医院详情
this.fetachHospDetail(id)
},
methods:{
//根据id查询医院详情
fetachHospDetail(id){
hospApi.getHospById(id)
.then(response => {
this.hospital = response.data.hospital
this.bookingRule = response.data.bookingRule
})
},
//返回列表
back(){
this.$router.push({path: '/hospset/hosp/list'})
}
}
}
</script>
4.3 添加详情样式文件
改样式文件是控制详情展示的css布局文件
1,/src/styles目录下创建show.css
.app-container{
background: #fff;
position: absolute;
width:100%;
height: 100%;
overflow: auto;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
.table-bordered {
border: 1px solid #ddd;
}
.table-striped>tbody>tr:nth-child(odd)>td, .table-striped>tbody>tr:nth-child(odd)>th {
background-color: #f9f9f9;
}
.table>thead>tr>th, .table>tbody>tr>th, .table>tfoot>tr>th,
.table>thead>tr>td, .table>tbody>tr>td, .table>tfoot>tr>td {
font-size: 14px;
color: #333;
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}
.table>thead>tr>th, .table>tbody>tr>th, .table>tfoot>tr>th{
text-align: right;
width: 120px;
}
.table-bordered>thead>tr>th, .table-bordered>tbody>tr>th, .table-bordered>tfoot>tr>th, .table-bordered>thead>tr>td, .table-bordered>tbody>tr>td, .table-bordered>tfoot>tr>td {
border: 1px solid #ddd;
}
.active_content{
padding: 0 20px ;
border-radius: 4px;
border: 1px solid #ebeef5;
background-color: #fff;
overflow: hidden;
color: #303133;
transition: .3s;
box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}
.active_content h4{
/*line-height: 0;*/
}
.active_content span{
font-size: 12px;
color: #999;
}
2,在src/main.js文件添加引用
import '@/styles/show.css'
5.排班管理
排班分成三部分显示:
1、科室信息(大科室与小科室树形展示)
2、排班日期,分页显示,根据上传排班数据聚合统计产生
3、排班日期对应的就诊医生信息
接口分析
1,科室数据使用Element-ui el-tree组件渲染展示,需要将医院上传的科室数据封装成两层父子级数据;
2,聚合所有排班数据,按日期分页展示,并统计号源数据展示;
3,根据排班日期获取排班详情数据
实现分析
虽然是一个页面展示所有内容,但是页面相对复杂,我们分步骤实现
1,先实现左侧科室树形展示;
2,其次排班日期分页展示
3,最后根据排班日期获取排班详情数据
5.1 科室列表
5.1.1 api接口
添加service接口与实现
在DepartmentService类添加接口
//根据医院编号,查询医院所有科室列表
List<DepartmentVo> findDeptTree(String hoscode);
在DepartmentServiceImpl类实现接口
//根据医院编号,查询医院所有科室列表
@Override
public List<DepartmentVo> findDeptTree(String hoscode) {
//创建list集合,用于最终数据封装
List<DepartmentVo> result = new ArrayList<>();
根据医院编号,查询医院所有科室信息
Department departmentQuery = new Department();
departmentQuery.setHoscode(hoscode);
Example example = Example.of(departmentQuery);
//所有科室列表 departmentList
List<Department> bigList = departmentRepository.findAll(example);
//根据大科室编号 bigcode 分组,获取每个大科室里面下级子科室
Map<String, List<Department>> bigMap = bigList.stream().collect(Collectors.groupingBy(Department::getBigcode));
//遍历map集合
for(Map.Entry<String,List<Department>> entry : bigMap.entrySet()){
//大科室的编号
String bigcode = entry.getKey();
//大科室标号对应的全部数据
List<Department> departmentList = entry.getValue();
//封装大科室
DepartmentVo bigVo = new DepartmentVo();
bigVo.setDepcode(bigcode);
bigVo.setDepname(departmentList.get(0).getBigname());
//封装小科室
List<DepartmentVo> children = new ArrayList<>();
for (Department department : departmentList) {
DepartmentVo departmentVo = new DepartmentVo();
departmentVo.setDepcode(department.getDepcode());
departmentVo.setDepname(department.getDepname());
//封装到list集合
children.add(departmentVo);
}
//把小科室list集合放到大科室children里面
bigVo.setChildren(children);
//放到最终的result中
result.add(bigVo);
}
return result;
}
添加controller接口
创建com.myproject.yygh.hosp.controller.DepartmentController类
package com.myproject.yygh.hosp.controller;
import com.myproject.yygh.common.result.Result;
import com.myproject.yygh.hosp.service.DepartmentService;
import com.myproject.yygh.vo.hosp.DepartmentVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/admin/hosp/department")
@CrossOrigin
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
//根据医院编号,查询医院所有科室列表
@ApiOperation(value = "查询医院所有科室列表")
@GetMapping("getDeptList/{hoscode}")
public Result getDeptList(@PathVariable String hoscode){
List<DepartmentVo> list = departmentService.findDeptTree(hoscode);
return Result.ok(list);
}
}
在swagger中测试接口
http://localhost:8201/swagger-ui.html
5.1.2 科室前端
添加路由
在 src/router/index.js 文件添加排班隐藏路由
添加在“查看”下面
{
path: 'hospital/schedule/:hoscode',
name: '排班',
component: () => import('@/views/hosp/schedule'),
meta: {
title: '排班', noicon: true },
hidden:true
}
添加按钮
在医院列表页面,添加排班按钮
/src/views/hosp/list.vue
<router-link :to="'/hospSet/hospital/schedule/'+scope.row.hoscode">
<el-button type="primary" size="mini">排班</el-button>
</router-link>
封装api请求
//查看医院科室
getDeptByHoscode(hoscode){
return request({
url:`/admin/hosp/department/getDeptList/${
hoscode}`,
method:'get'
})
}
部门展示
添加/views/hosp/schedule.vue组件
<template>
<div class="app-container">
<div style="margin-bottom: 10px;font-size: 10px;">选择:</div>
<el-container style="height: 100%">
<el-aside width="200px" style="border: 1px silver solid">
<!-- 部门 -->
<el-tree
:data="data"
:props="defaultProps"
:default-expand-all="true"
@node-click="handleNodeClick">
</el-tree>
</el-aside>
<el-main style="padding: 0 0 0 20px;">
<el-row style="width: 100%">
<!-- 排班日期 分页 -->
</el-row>
<el-row style="margin-top: 20px;">
<!-- 排班日期对应的排班医生 -->
</el-row>
</el-main>
</el-container>
</div>
</template>
<script>
import hospApi from '@/api/hosp'
export default {
data(){
return{
data: [],
defaultProps: {
children: 'children',
label: 'depname'
},
hoscode: null
}
},
created() {
this.hoscode = this.$route.params.hoscode
this.fetchData()
},
methods:{
fetchData(){
hospApi.getDeptByHoscode(this.hoscode)
.then(response => {
this.data = response.data
})
}
}
}
</script>
<style>
.el-tree-node.is-current > .el-tree-node__content {
background-color: #409EFF !important;
color: white;
}
.el-checkbox__input.is-checked+.el-checkbox__label {
color: black;
}
</style>
说明:底部style标签是为了控制树形展示数据选中效果的
5.2 排班日期分页列表
5.2.1 api接口
添加service接口与实现
在ScheduleService类添加接口
//根据医院编号 和科室编号 ,查询排班规则数据
Map<String, Object> getScheduleRule(Long page, Long limit, String hoscode, String depcode);
在ScheduleServiceImpl类实现接口
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private HospitalService hospitalService;
//根据医院编号 和科室编号 ,查询排班规则数据
@Override
public Map<String, Object> getScheduleRule(Long page, Long limit, String hoscode, String depcode) {
//1.根据医院编号和科室编号查询
Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
//2.通过个工作日期workDate进行分组
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(criteria),//匹配条件
Aggregation.group("workDate")//分组字段
.first("workDate").as("workDate")
//3.统计号源数量
.count().as("docCount")
.sum("reservedNumber").as("reservedNumber")
.sum("availableNumber").as("availableNumber"),
//排序
Aggregation.sort(Sort.Direction.DESC,"workDate"),
//4.实现分页
Aggregation.skip((page-1)*limit),
Aggregation.limit(limit)
);
//调用方法,最终执行
AggregationResults<BookingScheduleRuleVo> aggResult = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResult.getMappedResults();
//分组查询的总记录数
Aggregation totalAgg = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.group("workDate")
);
AggregationResults<BookingScheduleRuleVo> totalAggResult = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
int total = totalAggResult.getMappedResults().size();
//把日期对应星期获取
for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
Date workDate = bookingScheduleRuleVo.getWorkDate();
String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
}
//设置最终数据,进行返回
Map<String,Object> result = new HashMap<>();
result.put("bookingScheduleRuleVoList",bookingScheduleRuleVoList);
result.put("total",total);
//获取医院名称
Hospital hospital = hospitalService.getByHoscode(hoscode);
String hosName = null;
if(hospital != null){
hosName = hospital.getHosname();
}
//其他基础数据
Map<String,Object> baseMap = new HashMap<>();
baseMap.put("hosname",hosName);
result.put("baseMap",baseMap);
return result;
}
/**
* 根据日期获取周几数据
* @param dateTime
* @return
*/
private String getDayOfWeek(DateTime dateTime) {
String dayOfWeek = "";
switch (dateTime.getDayOfWeek()) {
case DateTimeConstants.SUNDAY:
dayOfWeek = "周日";
break;
case DateTimeConstants.MONDAY:
dayOfWeek = "周一";
break;
case DateTimeConstants.TUESDAY:
dayOfWeek = "周二";
break;
case DateTimeConstants.WEDNESDAY:
dayOfWeek = "周三";
break;
case DateTimeConstants.THURSDAY:
dayOfWeek = "周四";
break;
case DateTimeConstants.FRIDAY:
dayOfWeek = "周五";
break;
case DateTimeConstants.SATURDAY:
dayOfWeek = "周六";
default:
break;
}
return dayOfWeek;
}
添加controller接口
添加com.myproject.yygh.hosp.controller.ScheduleController类
package com.myproject.yygh.hosp.controller;
import com.myproject.yygh.common.result.Result;
import com.myproject.yygh.hosp.service.ScheduleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/admin/hosp/schedule")
@CrossOrigin
public class ScheduleController {
@Autowired
private ScheduleService scheduleService;
//根据医院编号 和科室编号 ,查询排班规则数据
@ApiOperation(value = "查询排班规则数据")
@GetMapping("getScheduleRule/{page}/{limit}/{hoscode}/{depcode}")
public Result getScheduleRule(@PathVariable Long page,
@PathVariable Long limit,
@PathVariable String hoscode,
@PathVariable String depcode){
Map<String,Object> map = scheduleService.getScheduleRule(page,limit,hoscode,depcode);
return Result.ok(map);
}
}
测试
http://localhost:8201/swagger-ui.html
输入参数如下:
page : 1
limit : 5
hoscode : 1000_0
depcode : 200040878
5.2.2 排班日期前端
封装api请求
src/api/hosp.js
//查询预约规则
getScheduleRule(page,limit,hoscode,depcode){
return request({
url:`/admin/hosp/schedule/getScheduleRule/${
page}/${
limit}/${
hoscode}/${
depcode}`,
method:'get'
})
}
修改/views/hosp/schedule.vue组件
<template>
<div class="app-container">
<div style="margin-bottom: 10px;font-size: 10px;">
选择:{
{
baseMap.hosname }} / {
{
depname }} / {
{
workDate }}</div>
<el-container style="height: 100%">
<el-aside width="200px" style="border: 1px silver solid">
<!-- 部门 -->
<el-tree
:data="data"
:props="defaultProps"
:default-expand-all="true"
@node-click="handleNodeClick">
</el-tree>
</el-aside>
<el-main style="padding: 0 0 0 20px;">
<el-row style="width: 100%">
<!-- 排班日期 分页 -->
<el-tag v-for="(item,index) in bookingScheduleList" :key="item.id" @click="selectDate(item.workDate, index)" :type="index == activeIndex ? '' : 'info'" style="height: 60px;margin-right: 5px;margin-right:15px;cursor:pointer;">
{
{
item.workDate }} {
{
item.dayOfWeek }}<br/>
{
{
item.availableNumber }} / {
{
item.reservedNumber }}
</el-tag>
<!-- 分页 -->
<el-pagination
:current-page="page"
:total="total"
:page-size="limit"
class="pagination"
layout="prev, pager, next"
@current-change="getPage">
</el-pagination>
</el-row>
<el-row style="margin-top: 20px;">
<!-- 排班日期对应的排班医生 -->
</el-row>
</el-main>
</el-container>
</div>
</template>
<script>
import hospApi from '@/api/hosp'
export default {
data(){
return{
data: [],
defaultProps: {
children: 'children',
label: 'depname'
},
hoscode: null,
activeIndex:0,
depcode:null,
depname:null,
workDate:null,
bookingScheduleList:[],
baseMap:{
},
page:1, //当前页
limit:7, //每页个数
total:0 //总页码
}
},
created() {
this.hoscode = this.$route.params.hoscode
this.workDate = this.getCurDate()
this.fetchData()
},
methods:{
fetchData(){
hospApi.getDeptByHoscode(this.hoscode)
.then(response => {
this.data = response.data
// 默认选中第一个
if (this.data.length > 0) {
this.depcode = this.data[0].children[0].depcode
this.depname = this.data[0].children[0].depname
this.getPage()
}
})
},
getPage(page = 1) {
this.page = page
this.workDate = null
this.activeIndex = 0
this.getScheduleRule()
},
getScheduleRule() {
hospApi.getScheduleRule(this.page, this.limit, this.hoscode, this.depcode).then(response => {
this.bookingScheduleList = response.data.bookingScheduleRuleVoList
this.total = response.data.total
this.scheduleList = response.data.scheduleList
this.baseMap = response.data.baseMap
// 分页后workDate=null,默认选中第一个
if (this.workDate == null) {
this.workDate = this.bookingScheduleList[0].workDate
}
})
},
handleNodeClick(data) {
// 科室大类直接返回
if (data.children != null) return
this.depcode = data.depcode
this.depname = data.depname
this.getPage(1)
},
selectDate(workDate, index) {
this.workDate = workDate
this.activeIndex = index
},
getCurDate() {
var datetime = new Date()
var year = datetime.getFullYear()
var month = datetime.getMonth() + 1 < 10 ? '0' + (datetime.getMonth() + 1) : datetime.getMonth() + 1
var date = datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate()
return year + '-' + month + '-' + date
}
}
}
</script>
<style>
.el-tree-node.is-current > .el-tree-node__content {
background-color: #409EFF !important;
color: white;
}
.el-checkbox__input.is-checked+.el-checkbox__label {
color: black;
}
</style>
5.3 根据排班日期获取排班详情列表
5.3.1 api接口
添加repository接口
在ScheduleRepository类添加接口
//根据医院编号,科室编号和工作日期,查询排班详细信息
List<Schedule> findScheduleByHoscodeAndDepcodeAndWorkDate(String hoscode, String depcode, Date toDate);
添加service接口与实现
在ScheduleService类添加接口
//根据医院编号,科室编号和工作日期,查询排班详细信息
List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate);
在ScheduleServiceImpl类实现接口
@Autowired
private DepartmentService departmentService;
//根据医院编号,科室编号和工作日期,查询排班详细信息
@Override
public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
//根据参数查询mongodb
List<Schedule> scheduleList =
scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());
//得到list集合遍历,向设置其他值:医院名称、科室名称、日期对应星期
scheduleList.stream().forEach(item -> {
this.packageSchedule(item);
});
return scheduleList;
}
//封装排班详情其他值:医院名称、科室名称、日期对应星期
private void packageSchedule(Schedule schedule) {
//设置医院名称
Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
String hosName = null;
if(hospital != null){
hosName = hospital.getHosname();
}
schedule.getParam().put("hosname",hosName);
//设置科室名称
schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
//设置日期对应星期
schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
}
添加根据部门编码获取部门名称
在DepartmentService类添加接口
//根据科室编号和医院编号查询科室名称
Object getDepName(String hoscode, String depcode);
在DepartmentService类添加接口实现
//根据科室编号和医院编号查询科室名称
@Override
public Object getDepName(String hoscode, String depcode) {
Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
if(department != null){
return department.getDepname();
}
return null;
}
添加controller
//根据医院编号,科室编号和工作日期,查询排班详细信息
@ApiOperation(value = "查询排班详细信息")
@GetMapping("getScheduleDetail/{hoscode}/{depcode}/{workDate}")
public Result getScheduleDetail(@PathVariable String hoscode,
@PathVariable String depcode,
@PathVariable String workDate){
List<Schedule> list = scheduleService.getDetailSchedule(hoscode,depcode,workDate);
return Result.ok(list);
}
测试
http://localhost:8201/swagger-ui.html
参数:
hoscode:1000_0
depcode:200040878
workDate:2021-01-28
5.3.2 排班日期前端
封装api请求
src/api/hosp.js
//查询排班详情
getScheduleDetail(hoscode,depcode,workDate){
return request({
url:`/admin/hosp/schedule/getScheduleDetail/${
hoscode}/${
depcode}/${
workDate}`,
method:'get'
})
}
页面展示
修改/views/hosp/schedule.vue组件
<template>
<div class="app-container">
<div style="margin-bottom: 10px;font-size: 10px;">
选择:{
{
baseMap.hosname }} / {
{
depname }} / {
{
workDate }}</div>
<el-container style="height: 100%">
<el-aside width="200px" style="border: 1px silver solid">
<!-- 部门 -->
<el-tree
:data="data"
:props="defaultProps"
:default-expand-all="true"
@node-click="handleNodeClick">
</el-tree>
</el-aside>
<el-main style="padding: 0 0 0 20px;">
<el-row style="width: 100%">
<!-- 排班日期 分页 -->
<el-tag v-for="(item,index) in bookingScheduleList" :key="item.id" @click="selectDate(item.workDate, index)" :type="index == activeIndex ? '' : 'info'" style="height: 60px;margin-right: 5px;margin-right:15px;cursor:pointer;">
{
{
item.workDate }} {
{
item.dayOfWeek }}<br/>
{
{
item.availableNumber }} / {
{
item.reservedNumber }}
</el-tag>
<!-- 分页 -->
<el-pagination
:current-page="page"
:total="total"
:page-size="limit"
class="pagination"
layout="prev, pager, next"
@current-change="getPage">
</el-pagination>
</el-row>
<el-row style="margin-top: 20px;">
<!-- 排班日期对应的排班医生 -->
<el-table
v-loading="listLoading"
:data="scheduleList"
border
fit
highlight-current-row>
<el-table-column
label="序号"
width="60"
align="center">
<template slot-scope="scope">
{
{
scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column label="职称" width="150">
<template slot-scope="scope">
{
{
scope.row.title }} | {
{
scope.row.docname }}
</template>
</el-table-column>
<el-table-column label="号源时间" width="80">
<template slot-scope="scope">
{
{
scope.row.workTime == 0 ? "上午" : "下午" }}
</template>
</el-table-column>
<el-table-column prop="reservedNumber" label="可预约数" width="80"/>
<el-table-column prop="availableNumber" label="剩余预约数" width="100"/>
<el-table-column prop="amount" label="挂号费(元)" width="90"/>
<el-table-column prop="skill" label="擅长技能"/>
</el-table>
</el-row>
</el-main>
</el-container>
</div>
</template>
<script>
import hospApi from '@/api/hosp'
export default {
data(){
return{
data: [],
defaultProps: {
children: 'children',
label: 'depname'
},
hoscode: null,
activeIndex:0,
depcode:null,
depname:null,
workDate:null,
bookingScheduleList:[],
baseMap:{
},
page:1, //当前页
limit:7, //每页个数
total:0, //总页码
scheduleList:[], //排班详情
listLoading:false
}
},
created() {
this.hoscode = this.$route.params.hoscode
this.workDate = this.getCurDate()
this.fetchData()
},
methods:{
//查询排班详情
getDetailSchedule(){
hospApi.getScheduleDetail(this.hoscode,this.depcode,this.workDate)
.then(response => {
console.log(response.data)
this.scheduleList = response.data
})
},
fetchData(){
hospApi.getDeptByHoscode(this.hoscode)
.then(response => {
this.data = response.data
// 默认选中第一个
if (this.data.length > 0) {
this.depcode = this.data[0].children[0].depcode
this.depname = this.data[0].children[0].depname
this.getPage()
}
this.scheduleList=null
//调用查询排班详情
this.getDetailSchedule()
})
},
getPage(page = 1) {
this.page = page
this.workDate = null
this.activeIndex = 0
this.getScheduleRule()
},
getScheduleRule() {
hospApi.getScheduleRule(this.page, this.limit, this.hoscode, this.depcode).then(response => {
this.bookingScheduleList = response.data.bookingScheduleRuleVoList
this.total = response.data.total
this.scheduleList = response.data.scheduleList
this.baseMap = response.data.baseMap
// 分页后workDate=null,默认选中第一个
if (this.workDate == null) {
this.workDate = this.bookingScheduleList[0].workDate
}
})
},
handleNodeClick(data) {
// 科室大类直接返回
if (data.children != null) return
this.depcode = data.depcode
this.depname = data.depname
this.getPage(1)
},
selectDate(workDate, index) {
this.scheduleList=null
this.workDate = workDate
this.activeIndex = index
//调用查询排班详情
this.getDetailSchedule()
},
getCurDate() {
var datetime = new Date()
var year = datetime.getFullYear()
var month = datetime.getMonth() + 1 < 10 ? '0' + (datetime.getMonth() + 1) : datetime.getMonth() + 1
var date = datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate()
return year + '-' + month + '-' + date
}
}
}
</script>
<style>
.el-tree-node.is-current > .el-tree-node__content {
background-color: #409EFF !important;
color: white;
}
.el-checkbox__input.is-checked+.el-checkbox__label {
color: black;
}
</style>
6.服务网关
网关介绍
API网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题:
(1)客户端会多次请求不同的微服务,增加了客户端的复杂性。
(2)存在跨域请求,在一定场景下处理相对复杂。
(3)认证复杂,每个服务都需要独立认证。
(4)难以重构,随着项目的迭代,可能需要重新划分微服务。例如,可能将多个服务合并成一个或者将一个服务拆分成多个。如果客户端直接与微服务通信,那么重构将会很难实施。
(5)某些微服务可能使用了防火墙 / 浏览器不友好的协议,直接访问会有一定的困难。
以上这些问题可以借助 API 网关解决。API 网关是介于客户端和服务器端之间的中间层,所有的外部请求都会先经过API 网关这一层。也就是说,API 的实现方面更多的考虑业务逻辑,而安全、性能、监控可以交由 API 网关来做,这样既提高业务灵活性又不缺安全性
6.1 Spring Cloud Gateway介绍
Spring cloud gateway是spring官方基于Spring 5.0、Spring Boot2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供简单、有效和统一的API路由管理方式,Spring Cloud Gateway作为Spring Cloud生态系统中的网关,目标是替代Netflix Zuul,其不仅提供统一的路由方式,并且还基于Filer链的方式提供了网关基本的功能,例如:安全、监控/埋点、限流等
6.2 搭建server-gateway模块
在yygh_parent下创建server_gateway模块
修改配置pom.xml
<dependencies>
<dependency>
<groupId>com.myproject</groupId>
<artifactId>common_util</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 服务注册 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
在resources下添加配置文件
application.yml
# 服务端口
server:
port: 81
spring:
application:
name: service-gateway # 服务名
cloud:
nacos:
server-addr: 127.0.0.1:8848 # nacos服务地址
gateway:
discovery:
locator:
enabled: true # 使用服务发现路由
routes:
- id: service-hosp # 设置路由id
uri: lb://service-hosp # 设置路由uri
predicates: #设置路由断言
- name: Path
args:
- /*/hosp/**
- id: service-cmn
uri: lb://service-cmn
predicates:
- name: Path
args:
- /*/cmn/**
添加启动类
package com.myproject.yygh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServerGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ServerGatewayApplication.class, args);
}
}
修改前端配置
yygh_page/config/dev.env.js
BASE_API: '"http://localhost:81"'
测试
记得关闭Nginx
6.3 解决跨域问题
全局配置类实现
com.myproject.yygh.config.CorsConfig类
package com.myproject.yygh.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
删除跨域注解
目前我们已经在网关做了跨域处理,那么service服务就不需要再做跨域处理了,将之前在controller类上添加过@CrossOrigin标签的去掉,防止程序异常
测试
重启前后端服务,然后测试