Day232233.排班管理模块需求分析、排班管理模块实现、服务网关整合代替之前的nginx

编程入门 行业动态 更新时间:2024-10-28 08:26:51

Day232233.排班<a href=https://www.elefans.com/category/jswz/34/1769095.html style=管理模块需求分析、排班管理模块实现、服务网关整合代替之前的nginx"/>

Day232233.排班管理模块需求分析、排班管理模块实现、服务网关整合代替之前的nginx

尚医通

一、排班管理

1、页面效果

排班分成三部分显示:

1、科室信息(大科室与小科室树形展示)

2、排班日期,分页显示,根据上传排班数据聚合统计产生

3、排班日期对应的就诊医生信息

2、接口分析

1,科室数据使用Element-ui el-tree组件渲染展示,需要将医院上传的科室数据封装成两层父子级数据;

2,聚合所有排班数据,按日期分页展示,并统计号源数据展示;

3,根据排班日期获取排班详情数据

3、实现分析

虽然是一个页面展示所有内容,但是页面相对复杂,我们分步骤实现

1,先实现左侧科室树形展示;

2,其次排班日期分页展示

3,最后根据排班日期获取排班详情数据

二、排班管理实现

1、科室列表

1.1 api接口

1.1.1 添加service接口与实现

在DepartmentService类添加接口

根据医院编号,查询医院所有科室列表
List<DepartmentVo> findDeptTree(String hoscode);

在DepartmentServiceImpl类实现接口

    //根据医院编号,查询医院所有科室列表@Overridepublic List<DepartmentVo> findDeptTree(String hoscode) {//创建list集合,用于封装最终的数据ArrayList<DepartmentVo> resultList = new ArrayList<>();//根据医院编号,查询医院所有科室信息Department department = new Department();department.setHoscode(hoscode);Example<Department> example = Example.of(department);//所有科室列表信息List<Department> departmentList = departmentRepository.findAll(example);//根据大科室编号 分组Map<String, List<Department>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));//遍历map集合for (Map.Entry<String,List<Department>> entry : departmentMap.entrySet()){//大科室编号String bigCode = entry.getKey();//大科室编号对应的全部数据List<Department> bigCodeList = entry.getValue();//封装大科室DepartmentVo departmentVo = new DepartmentVo();departmentVo.setDepcode(bigCode);departmentVo.setDepname(bigCodeList.get(0).getBigname());//封装小科室List<DepartmentVo> child = new ArrayList<>();for (Department department1 : bigCodeList) {//遍历大科室数据中的所有小科室DepartmentVo departmentVo1 = new DepartmentVo();departmentVo1.setDepcode(department1.getDepcode());departmentVo1.setDepname(department1.getDepname());//封装小科室child.add(departmentVo1);}//把小科室list集合放到大科室child对象中departmentVo.setChildren(child);//放入最终的返回集合中resultList.add(departmentVo);}return resultList;}
1.1.2 添加controller接口
@RestController
@RequestMapping("/admin/hosp/department")
@CrossOrigin
public class DepartmentController {@Autowiredprivate DepartmentService departmentService;//根据医院编号,查询医院所有科室列表@GetMapping("/getDeptList/{hoscode}")public Result getDeptList(@PathVariable String hoscode){List<DepartmentVo> list = departmentService.findDeptTree(hoscode);return Result.ok(list);}}

1.2 科室前端

1.2.1 添加路由

在 src/router/index.js 文件添加排班隐藏路由

      {path: 'hosp/schedule/:hoscode',name: '排班',component: ()=> import('@/views/hosp/schedule.vue'),meta:{title: '排班',icon:'table',nocache:'true'},hidden: true}
1.2.2 添加按钮

在医院列表页面,添加排班按钮

<router-link :to="'/hospSet/hosp/schedule/'+scope.row.hoscode"><el-button type="info" size="mini">查看排班</el-button>
</router-link>
1.2.3封装api请求
  //获取医院科室,根据医院编号getDeptByHoscode(hoscode){return request({url: `/admin/hosp/department/getDeptList/${hoscode}`,method: 'get'})}
1.2.4 部门展示

修改/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{hoscode:null,data:[],defaultProps:{children:'children',label:'depname'},}},created(){this.hoscode = this.$route.params.hoscodethis.getDeptByHoscode()},methods:{getDeptByHoscode(){hospAPI.getDeptByHoscode(this.hoscode).then(resp=>{this.data = resp.dataconsole.log(this.data)})},}
}
</script><style scoped>
.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标签是为了控制树形展示数据选中效果的

2、排班日期分页列表

2.1 api接口

2.1.1 添加service接口与实现

在ScheduleService类添加接口

//根据【医院编号】 【科室编号】,【分页查询】排版规则数据
Map<String, Object> getScheduleRulePage(long page, long limit, String hoscode, String depcode);

在ScheduleServiceImpl类实现接口

package com.achang.yygh.hosp.service.impl;import com.achang.exception.YyghException;
import com.achang.utils.DateUtil;
import com.achang.yygh.hosp.repository.ScheduleRepository;
import com.achang.yygh.hosp.service.HospitalService;
import com.achang.yygh.hosp.service.HospitalSetService;
import com.achang.yygh.hosp.service.ScheduleService;
import com.achang.yygh.model.hosp.Department;
import com.achang.yygh.model.hosp.Schedule;
import com.achang.yygh.vo.hosp.BookingScheduleRuleVo;
import com.achang.yygh.vo.hosp.ScheduleQueryVo;
import com.alibaba.fastjson.JSONObject;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Service
public class ScheduleServiceImpl implements ScheduleService {@Autowiredprivate MongoTemplate mongoTemplate;@Autowiredprivate HospitalService hospitalService;//根据【医院编号】 【科室编号】,【分页查询】排版规则数据@Overridepublic Map<String, Object> getScheduleRulePage(long page, long limit, String hoscode, String depcode) {//根据医院编号、科室编号 查询对应数据//封装查询条件Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);//根据工作日workDate期进行分组Aggregation agg = Aggregation.newAggregation(Aggregation.match(criteria),//条件匹配Aggregation.group("workDate")//分组字段.first("workDate").as("workDate")//设置分组后的别名.count().as("docCount")//统计号源数量并设置名字.sum("reservedNumber").as("reservedNumber")//求和reservedNumber字段.sum("availableNumber").as("availableNumber"),//求和availableNumber字段Aggregation.sort(Sort.Direction.DESC,"workDate"),//指定是升序还是降序,指定哪个字段排序//分页Aggregation.skip((page-1)*limit),//(当前页-1)*每页记录数Aggregation.limit(limit)//每页显示数);//得到分组查询后的总记录数Aggregation totalAgg = Aggregation.newAggregation(Aggregation.match(criteria),//条件查询Aggregation.group("workDate")//分组));AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);//获取总记录数int total = totalAggResults.getMappedResults().size();//调用方法最终执行//参数1:上面封装的条件//参数2:之前的实体类//参数3:最后封装的尸体类AggregationResults<BookingScheduleRuleVo> results = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);//获取到最终的集合List<BookingScheduleRuleVo> ruleVoList = results.getMappedResults();//把日期对应的星期获取出来for (BookingScheduleRuleVo bookingScheduleRuleVo:ruleVoList){Date workDate = bookingScheduleRuleVo.getWorkDate();//获取到星期几String week = DateUtil.getDayOfWeek(new DateTime(workDate));bookingScheduleRuleVo.setDayOfWeek(week);}//设置最终数据进行返回HashMap<String, Object> resultMap = new HashMap<>();resultMap.put("list",ruleVoList);resultMap.put("total",total);//根据医院编号,获取医院名称String hospName = hospitalService.getHospName(hoscode);//其他基础数据HashMap<String, String> baseMap = new HashMap<>();baseMap.put("hospName",hospName);resultMap.put("baseMap",baseMap);return resultMap;}/*** 根据日期获取周几数据* @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;}}
2.1.2 添加根据医院编号获取医院名称接口

在HospitalService类添加接口

    //根据医院编号,获取医院名称String getHospName(String hoscode);

在HospitalServiceImpl类实现接口

    //根据医院编号,获取医院名称@Overridepublic String getHospName(String hoscode) {Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);if (hospital!=null){return hospital.getHosname();}return null;}
2.1.3 添加controller接口

添加com.atguigu.yygh.hosp.controller.ScheduleController类

import com.achang.result.Result;
import com.achang.yygh.hosp.service.ScheduleService;
import com.achang.yygh.model.hosp.Schedule;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;
import java.util.Map;@RestController
@CrossOrigin
@RequestMapping("/admin/hosp/Schedule")
public class ScheduleController {@Autowiredprivate ScheduleService scheduleService;//根据【医院编号】 【科室编号】,【分页查询】排版规则数据@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.getScheduleRulePage(page,limit,hoscode,depcode);return Result.ok(map);}}
  • 测试


2.2 排班日期前端

1.2.1封装api请求

创建/api/hosp/schedule.js

import request from '@/utils/request'export default {//根据【医院编号】 【科室编号】,【分页查询】排版规则数据getScheduleRule(page,limit,hoscode,depcode) {return request({url: `/admin/hosp/Schedule/getScheduleRule/${page}/${limit}/${hoscode}/${depcode}`,method: 'get'})}}
1.2.2 页面展示

修改/views/hosp/schedule.vue组件

<template><div class="app-container"><div style="margin-bottom: 10px;font-size: 10px;">选择:{{ baseMap.hospName }} / {{ 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'
import scheduleAPI from '@/api/schedule'export default {data() {return {bookingScheduleList: [],hoscode: null,data: [],defaultProps: {children: 'children',label: 'depname'},activeIndex: 0,depcode: null,depname: null,workDate: null,baseMap: {},page: 1, // 当前页limit: 7, // 每页个数total: 0 // 总页码}},created() {this.hoscode = this.$route.params.hoscodethis.workDate = this.getCurDate()this.getDeptByHoscode()},methods: {getDeptByHoscode() {hospAPI.getDeptByHoscode(this.hoscode).then(resp => {this.data = resp.dataconsole.log(this.data)//默认选中第一个if (this.data.length > 0) {this.depcode = this.data[0].children[0].depcodethis.depname = this.data[0].children[0].depname//刷新页面this.getPage()}})},//得到当前日期getCurDate() {var datetime = new Date()var year = datetime.getFullYear()var month = datetime.getMonth() + 1 < 10 ? '0' + (datetime.getMonth() + 1) : datetime.getMonth() + 1var date = datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate()return year + '-' + month + '-' + date},//根据【医院编号】 【科室编号】,【分页查询】排版规则数据getScheduleRule() {scheduleAPI.getScheduleRule(this.page, this.limit, this.hoscode, this.depcode).then(resp => {console.log(resp.data)this.bookingScheduleList = resp.data.listthis.total = resp.data.totalthis.scheduleList = resp.data.scheduleListthis.baseMap = resp.data.baseMap// 分页后workDate=null,默认选中第一个if (this.workDate == null) {this.workDate = this.bookingScheduleList[0].workDate}})},//分页查询getPage(page = 1) {this.page = pagethis.workDate = nullthis.activeIndex = 0this.getScheduleRule()},handleNodeClick(data) {// 科室大类直接返回if (data.children != null) returnthis.depcode = data.depcodethis.depname = data.depnamethis.getPage(1)},selectDate(workDate, index) {this.workDate = workDatethis.activeIndex = index},}
}
</script><style scoped>
.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>
  • 效果显示


3、根据排班日期获取排班详情列表

3.1 api接口

3.1.1 添加repository接口

在ScheduleRepository类添加接口

//根据医院编号、科室编号、工作日期,查询排版详细信息
List<Schedule> findScheduleByHoscodeAndDepcodeAndWorkDate(String hoscode, String depcode, Date toDate);
3.1.2 添加service接口与实现

在ScheduleService类添加接口

//根据医院编号、科室编号、工作日期,查询排版详细信息
List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate);

在ScheduleServiceImpl类实现接口

//根据医院编号、科室编号、工作日期,查询排版详细信息
@Override
public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {//根据参数,查询mongodbList<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());//遍历list集合,设置每个元素对应的属性//使用stream流遍历scheduleList.stream().forEach(item->{this.packageSchedule(item);});return scheduleList;
}//封装其他值:医院名称,科室名称,日期对应的星期
private void packageSchedule(Schedule item) {Map<String, Object> map = item.getParam();//获取医院名称String hospName = hospitalService.getHospName(item.getHoscode());//根据医院编号、科室编号,获取科室名称String deptName = departmentService.getDeptName(item.getHoscode(),item.getDepcode());//获取日期对应的星期String week = DateUtil.getDayOfWeek(new DateTime(item.getWorkDate()));map.put("hospName",hospName);map.put("deptName",deptName);map.put("week",week);}

3.1.3 添加根据部门编码获取部门名称

1,在DepartmentService类添加接口

//根据医院编号、科室编号,获取科室名称
String getDeptName(String hoscode, String depcode);

2,在DepartmentService类添加接口实现

//根据医院编号、科室编号,获取科室名称
@Override
public String getDeptName(String hoscode, String depcode) {Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode);if (department!=null){return department.getDepname();}return null;
}
3.1.4 添加controller
//根据医院编号、科室编号、工作日期,查询排版详细信息
@GetMapping("/getScheduleDetail/{hoscode}/{depcode}/{workDate}")
public Result getScheduleDetail(@PathVariable String hoscode,@PathVariable String depcode,@PathVariable String workDate){List<Schedule> list = scheduleService.getScheduleDetail(hoscode,depcode,workDate);return Result.ok(list);
}

3.2 排班日期前端

3.2.1封装api请求

在/api/hosp/schedule.js文件添加方法

  //根据医院编号、科室编号、工作日期,查询排版详细信息getScheduleDetail(hoscode,depcode,workDate) {return request({url: `/admin/hosp/Schedule/getScheduleDetail/${hoscode}/${depcode}/${workDate}`,method: 'get'})},
1.2.2 页面展示

修改/views/hosp/schedule.vue组件

<template><div class="app-container"><div style="margin-bottom: 10px;font-size: 10px;">选择:{{ baseMap.hospName }} / {{ 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-tablev-loading="listLoading":data="scheduleList"borderfithighlight-current-row><el-table-columnlabel="序号"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'
import scheduleAPI from '@/api/schedule'export default {data() {return {bookingScheduleList: [],hoscode: null,data: [],defaultProps: {children: 'children',label: 'depname'},activeIndex: 0,depcode: null,depname: null,workDate: null,baseMap: {},page: 1, // 当前页limit: 7, // 每页个数total: 0, // 总页码scheduleList:[] //排班详细}},created() {this.hoscode = this.$route.params.hoscodethis.workDate = this.getCurDate()this.getDeptByHoscode()},methods: {getDeptByHoscode() {hospAPI.getDeptByHoscode(this.hoscode).then(resp => {this.data = resp.dataconsole.log(this.data)//默认选中第一个if (this.data.length > 0) {this.depcode = this.data[0].children[0].depcodethis.depname = this.data[0].children[0].depname//刷新页面this.getPage()}})},//得到当前日期getCurDate() {var datetime = new Date()var year = datetime.getFullYear()var month = datetime.getMonth() + 1 < 10 ? '0' + (datetime.getMonth() + 1) : datetime.getMonth() + 1var date = datetime.getDate() < 10 ? '0' + datetime.getDate() : datetime.getDate()return year + '-' + month + '-' + date},//根据【医院编号】 【科室编号】,【分页查询】排版规则数据getScheduleRule() {scheduleAPI.getScheduleRule(this.page, this.limit, this.hoscode, this.depcode).then(resp => {console.log(resp.data)this.bookingScheduleList = resp.data.listthis.total = resp.data.totalthis.scheduleList = resp.data.scheduleListthis.baseMap = resp.data.baseMap// 分页后workDate=null,默认选中第一个if (this.workDate == null) {this.workDate = this.bookingScheduleList[0].workDate}//查询排班细节信息this.getScheduleDetail()})},//根据医院编号、科室编号、工作日期,查询排版详细信息getScheduleDetail(){scheduleAPI.getScheduleDetail(this.hoscode,this.depcode,this.workDate).then(resp=>{this.scheduleList = resp.data})},//分页查询getPage(page = 1) {this.page = pagethis.workDate = nullthis.activeIndex = 0this.getScheduleRule()},handleNodeClick(data) {// 科室大类直接返回if (data.children != null) returnthis.depcode = data.depcodethis.depname = data.depnamethis.getPage(1)},selectDate(workDate, index) {this.workDate = workDatethis.activeIndex = index//查询排班细节信息this.getScheduleDetail()},}
}
</script><style scoped>
.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>
  • 效果


三、服务网关

1、网关介绍

API网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题:

(1)客户端会多次请求不同的微服务,增加了客户端的复杂性。

(2)存在跨域请求,在一定场景下处理相对复杂。

(3)认证复杂,每个服务都需要独立认证。

(4)难以重构,随着项目的迭代,可能需要重新划分微服务。例如,可能将多个服务合并成一个或者将一个服务拆分成多个。如果客户端直接与微服务通信,那么重构将会很难实施。

(5)某些微服务可能使用了防火墙 / 浏览器不友好的协议,直接访问会有一定的困难。

以上这些问题可以借助 API 网关解决。API 网关是介于客户端和服务器端之间的中间层,所有的外部请求都会先经过API 网关这一层。也就是说,API 的实现方面更多的考虑业务逻辑,而安全、性能、监控可以交由 API 网关来做,这样既提高业务灵活性又不缺安全性

2、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链的方式提供了网关基本的功能,例如:安全、监控/埋点、限流等

3、搭建server-gateway模块

服务网关

3.1 搭建server-gateway

搭建过程如common模块

3.2 修改配置pom.xml

修改pom.xml

<dependencies><dependency><groupId>com.achang</groupId><artifactId>common-util</artifactId><version>0.0.1-SNAPSHOT</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>

3.3 在resources下添加配置文件

1、application.properties

#服务端口
server.port=80#服务名
spring.application.name=service-gateway#nacos地址
spring.cloud.nacos.discovery.server-addr=localhost:8848#使用服务发现路由
spring.cloud.gateway.discovery.locator.enabled=true#设置路由id
spring.cloud.gateway.routes[0].id=service-hosp
#设置路由的uri
spring.cloud.gateway.routes[0].uri=lb://service-hosp
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[0].predicates= Path=/*/hosp/**#设置路由id
spring.cloud.gateway.routes[1].id=service-cmn
#设置路由的uri
spring.cloud.gateway.routes[1].uri=lb://service-cmn
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[1].predicates= Path=/*/cmn/**

3.4添加启动类

@SpringBootApplication
public class ServiceGatewayMain80 {public static void main(String[] args) {SpringApplication.run(ServiceGatewayMain80.class,args);}
}
  • nacos

3.5 跨域处理

跨域:浏览器对于javascript的同源策略的限制 。

以下情况都属于跨域:

跨域原因说明示例
域名不同www.jd 与 www.taobao
域名相同,端口不同www.jd:8080 与 www.jd:8081
二级域名不同item.jd 与 miaosha.jd

如果域名和端口都相同,但是请求路径不同,不属于跨域,如:

www.jd/item

www.jd/goods

http和https也属于跨域

而我们刚才是从localhost:1000去访问localhost:8888,这属于端口不同,跨域了。


3.5.1 为什么有跨域问题?

跨域不一定都会有跨域问题。

因为跨域问题是浏览器对于ajax请求的一种安全限制:一个页面发起的ajax请求,只能是与当前页域名相同的路径,这能有效的阻止跨站攻击。

因此:跨域问题 是针对ajax的一种限制。

但是这却给我们的开发带来了不便,而且在实际生产环境中,肯定会有很多台服务器之间交互,地址和端口都可能不同,怎么办?


3.5.2解决跨域问题

全局配置类实现

CorsConfig类,直接放着网关模块下的config包下

package com.achang.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;/******
GateWay跨域配置类*/
@Configuration
public class CorsConfig {@Beanpublic 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);}
}

3.6服务调整

目前我们已经在网关做了跨域处理,那么service服务就不需要再做跨域处理了

将之前在controller类上添加过@CrossOrigin标签的去掉,防止程序异常

  • 修改前端的访问地址


3.7测试

通过平台与管理平台前端测试


更多推荐

Day232233.排班管理模块需求分析、排班管理模块实现、服务网关整合代替之前的nginx

本文发布于:2024-02-10 20:21:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1677095.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:管理模块   网关   需求   nginx

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!