目录
一、注册中心与服务调用:
目前在医院列表中需要医院的信息和等级信息,而两段信息属于不同的的模块,service-hosp和service-cmn,所以我们需要使用到远程调用。
1、Nacos概述
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结构图
1.4 Nacos下载和安装
下载地址:https://github.com/alibaba/nacos/releases
下载版本:nacos-server-1.1.4.tar.gz或nacos-server-1.1.4.zip,解压任意目录即可
启动Nacos服务:
Linux/Unix/Mac
启动命令(standalone代表着单机模式运行,非集群模式)
启动命令:sh startup.sh -m standalone
Windows:
启动命令:cmd startup.cmd 或者双击startup.cmd运行文件。
访问:http://localhost:8848/nacos
用户名密码:nacos/nacos
2、注册服务
2.1 Nacos注册service-hosp
第一步:在service模块pom文件引入依赖
在service父工程的pom中增加nacos依赖:
<!-- 服务注册 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
第二步:在service-hosp的配置文件添加nacos服务地址:
nacos服务地址:
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
第三步:在service-hosp的启动类添加注解:@EnableDiscoveryClient
@SpringBootApplication
@ComponentScan(basePackages = "com.atguigu")
@EnableDiscoveryClient
public class ServiceHospApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceHospApplication.class, args);
}
}
启动service-hosp服务,在Nacos管理界面的服务列表中可以看到注册的服务
service-cmn注册过程和service-hosp相同(省略)
二、医院管理实现
1、医院列表
1.1 医院列表api接口
添加controller方法
添加com.fan.yygh.hosp.controller.HospitalController类
package com.atguigu.yygh.hosp.controller;
@Api(tags = "医院管理接口")
@RestController
@RequestMapping("/admin/hosp/hospital")
public class HospitalController {
@Autowired
private HospitalService hospitalService;
@ApiOperation(value = "获取分页列表")
@GetMapping("{page}/{limit}")
public Result index(
@ApiParam(name = "page", value = "当前页码", required = true)
@PathVariable Integer page,
@ApiParam(name = "limit", value = "每页记录数", required = true)
@PathVariable Integer limit,
@ApiParam(name = "hospitalQueryVo", value = "查询对象", required = false)
HospitalQueryVo hospitalQueryVo) {
return Result.ok(hospitalService.selectPage(page, limit, hospitalQueryVo));
}
}
1.1.1 添加service分页接口与实现:
@Override
public Page<Hospital> getHospitalByPage(Integer page,
Integer limit,
HospitalQueryVo hospitalQueryVo) {
//使用mongodb进行分页
Pageable pageable = PageRequest.of(page-1, limit);
Hospital hospital = new Hospital();
//返回值为空,使用工具转换时异常了。如果是自己封装的类转换工具类的话,记得把判空加上
if(hospitalQueryVo != null){
BeanUtils.copyProperties(hospitalQueryVo,hospital);
}
System.out.println("hospital:"+hospital);
//条件分页
ExampleMatcher exampleMatcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase(true);
Example<Hospital> example =
Example.of(hospital, exampleMatcher);
Page<Hospital> all = hospitalRepository.findAll(example, pageable);
return all;
}
在HospitalService类添加分页接口:
Page<Hospital> getHospitalByPage(Integer page,
Integer limit, HospitalQueryVo hospitalQueryVo);
1.2 service-cmn模块提供接口
这里是提供查询的接口:
由于我们的医院等级、省市区地址都是取的数据字典value值,因此我们在列表显示医院等级与医院地址时要根据数据字典value值获取数据字典名称
通过学习数据字典我们知道,根据上级编码与value值可以获取对应的数据字典名称,如果value值能够保持唯一(不一定唯一),我们也可以直接通过value值获取数据字典名称,目前省市区三级数据我们使用的是国家统计局的数据,数据编码我们就是数据字典的id与value,所以value能够唯一确定一条数据字典,如图:
//根据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;
}
getDictName的实现方法:用于返回数据字典名称:
/*
此方法用于返回数据字典名称
* */
//如果value能唯一定位数据字典,parentDictCode可以传空,例如:省市区的value值能够唯一确定
@Override //根据dictCode 和value查询,controller中是2个重载的方法,这里都汇总成一个了
@Cacheable(cacheNames = "dict",keyGenerator = "keyGenerator")
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 codeDict = this.getDictByDictCode(dictCode);
//,得到本条数据的dict的id值
Long parent_id = codeDict.getId();
//根据parent_id和value值进行查询,
// 即我们开始是由dictCode转到查询本条数据的id,
// 然后由本条数据的id联系到其他数据的相同的parent_id,然后转而查询parent_id和value
//来得到唯一的dict实体类数据,然后获得他的name
Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
.eq("parent_id", parent_id)
.eq("value", value));
return finalDict.getName();
}
}
//根据dictcode获取本条数据
private Dict getDictByDictCode(String dictCode){
QueryWrapper<Dict> wrapper = new QueryWrapper<>();
wrapper.eq("dict_code",dictCode);
Dict codeDict = baseMapper.selectOne(wrapper);
return codeDict;
}
测试:
1.3封装Feign服务调用
1.3.1搭建service-client父模块
在yygh_parent下搭建子模块:
1.3.2 搭建service-cmn-client模块
搭建过程如service-hosp模块
添加Feign接口类:
复制controller接口:
Feign接口类代码:
package com.fan.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;
/*此类封装远程调用的接口*/
/*1.微服务之间需要相互调用,第一个是需要注册中心,把所有的微服务注册进去
* 2.如果微服务之间需要调用沟通,还需要一个服务调用的组件openfeign,就好比
* 我们去房产中心租房子,都要注册自己的信息到房产中心,然后当你需要租房的时候,
* 需要进行服务的调用,服务调用也需要一个接口组件,如电话接口一样,通过电话去进行
* 服务的调用。这里的电话就是一个服务调用的interface接口 */
@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);
}
1.4医院接口远程调用数据字典:
1.4.1 service模块引入依赖
在pom.xml添加依赖:
<!-- 服务调用feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
1.4.2 操作service-hosp模块
1.4.2.1在service-hosp添加依赖
<dependency>
<groupId>com.atguigu.yygh</groupId>
<artifactId>service-cmn-client</artifactId>
<version>1.0</version>
</dependency>
1.4.2.2 启动类开启服务调用:
@SpringBootApplication
@ComponentScan(basePackages = "com.atguigu")
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.atguigu")
public class ServiceHospApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceHospApplication.class, args);
}
}
1.4.2.3调整service方法
修改HospitalServiceImpl类实现分页
、
@Override //医院条件分页查询,分页的逻辑都是在impl中的
public Page<Hospital> selectHospPage(Integer page, Integer limit,
HospitalQueryVo hospitalQueryVo) {
//Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
//Pageable pageable = PageRequest.of(page-1, limit, sort);
//分页第一步:创建pageable对象
Pageable pageable = PageRequest.of(page-1, limit);
//分页第二步:创建条件匹配器
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式:模糊查询
.withIgnoreCase(true);//改变默认大小写忽略方式:忽略大小写
//分页第三步:分页条件对象的转换
Hospital hospital = new Hospital();
if(hospitalQueryVo != null){
BeanUtils.copyProperties(hospitalQueryVo,hospital);
}
//分页第四步:创建example对象
Example<Hospital> example = Example.of(hospital, matcher);
//分页第五步:Repository调用分页方法
Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
//分页完毕===============对分页进行医院等级和省市区的增加===========================
//修改这里,进行远程调用
pages.getContent().stream().forEach(item -> {
//获取查询list集合,遍历进行医院等级和省市级的封装
this.setHospitalHosType(item);//远程调用
});
return pages;
}
//获取查询list集合,遍历进行医院等级和省市级的封装
private Hospital setHospitalHosType(Hospital hospital) {
//根据dictCode和value远程获取医院等级名称
/*dictFeignClient为服务调用的接口 */
String hostypeString = dictFeignClient.getName(
"Hostype", hospital.getHostype());
System.out.println(hospital.getHostype());
System.out.println(hospital.getProvinceCode());
//查询省市区,远程调用 服务调用的接口,getProvinceCode获取对应的dictcode
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;
}
启动数据字典模块和service_hosp模块:
测试接口:GET /admin/hosp/hospital/list/{page}/{limit}
此接口封装了医院的等级和省市区:
1.5 添加数据字典显示接口:
1.5.1 编写controller
根据dicode查询下层节点
@ApiOperation(value = "根据dictCode获取下级节点")
@GetMapping(value = "/findByDictCode/{dictCode}")
public Result<List<Dict>> findByDictCode(
@ApiParam(name = "dictCode", value = "节点编码", required = true)
@PathVariable String dictCode) {
List<Dict> list = dictService.findByDictCode(dictCode);
return Result.ok(list);
}
1.5.2 编写service
根据dicode查询下层节点
@Override
public List<Dict> findByDictCode(String dictCode) {
Dict codeDict = this.getDictByDictCode(dictCode);
if(null == codeDict) return null;
return this.findChlidData(codeDict.getId());
}
打开这个注释:
测试成功;
前端的页面:
省市联动的条件查询的接口:
实现类代码:
/*======================省市级联动的条件查询实现方法========================*/
@Override //具体怎么根据dictcode获取下级节点
@Cacheable(cacheNames = "dict",keyGenerator = "keyGenerator")
public List<Dict> findByDictCode(String dictCode) {
//1.根据dictcode 获取那一条数据的对应id
Dict dict = this.getDictByDictCode(dictCode);
//2.根据本条数据的id找到子节点
List<Dict> childData = this.findChildData(dict.getId());
return childData;
}
//1.根据dictcode获取本条数据
private Dict getDictByDictCode(String dictCode){
QueryWrapper<Dict> wrapper = new QueryWrapper<>();
wrapper.eq("dict_code",dictCode);
Dict codeDict = baseMapper.selectOne(wrapper);
return codeDict;
}
@Override //2.根据本条数据的id找到子节点,参数是本条数据的id
@Cacheable(value = "dict",keyGenerator = "keyGenerator")
public List<Dict> findChildData(long id) {//这里的参数本质是一个父级id,如1
QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//即条件是parent_id==id,即字典的父级id等于参数id时,返回那些数据
//根据父级id查询多个集合的dict实体数据
wrapper.eq("parent_id",id);//parent_id=1的有数据电脑,医院等级。。。
List<Dict> dictList = baseMapper.selectList(wrapper);
//向list集合每个dict对象中设置hasChildren字段值
for (Dict dict : dictList) {
Long dictId = dict.getId();//查出每个二级字典自己的主id
//根据每条数据的本身id再去查询表,看是否还有父级id
boolean isChild = this.isChildren(dictId);
dict.setHasChildren(isChild);
}
return dictList;
}
测试后台的省市联动条件查询的接口:
http://localhost:8202/admin/cmn/dict/findByDictCode/Province
前端页面开始:
效果:
页面:
import request from '@/utils/request'
export default {
//1.医院列表
getHospList(page,limit,searchObj) {
return request ({
url: `/admin/hosp/hospital/list/${page}/${limit}`,
method: 'get',
params: searchObj
})
},
//2.根据dictcode查询所有的子节点(所有省)===========这里就是省级联动的省的前端==================
findByDictCode(dictCode){
return request ({
url: `/admin/cmn/dict/findByDictCode/${dictCode}`,
method: 'get'
})
},
//==================根据所有的省查询旗下的所有市=================
//3.根据数据id查询子数据列表
findChildId(id){
return request ({
url: `/admin/cmn/dict/findChildData/${id}`,
method: 'get'
})
},
this. fetchData(this.page);
页面的省份在这里显示:
总的医院的hosp/list.vue页面的js:
<script>
import hospApi from '@/api/hosp';
export default {
data() {
return {
listLoading: false, // 数据是否正在加载
list: null, // 医院列表数据集合
total: 0, // 数据库中的总记录数
page: 1, // 默认页码
limit: 10, // 每页记录数
searchObj: {}, // 查询表单对象
provinceList: [], //所有省集合
cityList: [] //所有市集合
}
},
created(){
//调用医院列表
this.fetchData(); //this.fetchData(this.page)
//调用查询所有省的方法:
this.findAllProvince();
},
methods: {
//1.医院列表
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
})
},
//2.查询所有省
findAllProvince(){
hospApi.findByDictCode('Province')
.then(response => {
this.provinceList = response.data; //将所有的省放到集合中
})
},
//3.点击某个省,显示里面的市区()联动
provinceChanged() {
//初始化值
this.cityList = [];
this.searchObj.cityCode = null
//调用方法,根据省id,查询下面子节点
hospApi.findChildId(this.searchObj.provinceCode)
.then(response => {
this.cityList = response.data;
})
},
//4.分页,页码变化
changeSize() {
this.limit = size;
this.fetchData(1);
},
//5.更新医院上线状态
updateStatus(id, status) {
hospApi.updateStatus(id, status).then((response) => {
this.fetchData(this.page);
});
}
}
}
</script>
测试遇到问题:
问题总结:前端在这里卡住了:
市选择不显示的在数据那边给searchObj里面写上provinceCode:‘’,cityCode:''或者使用强制渲染
选择了市不显示 的可以修改@change为$forceUpdate()
cityChange()自己加一下吧 和provinceChange()差不多的
不显示市的,去实现cityChanged方法,里面调用查所有医院的方法
问题解决:
由于自己粗心,这里的一个方法名字被直接被换到下一行了,导致数据不出来:
改正后测试:
2、更新医院上线状态
医院的信息数据存储在mongodb中:
2.1 api接口
添加controller方法
在HospitalController类添加方法
@ApiOperation("//更新医院上线状态_my")
@PutMapping("updateHospStatus_my/{id}/{status}")
public Result updateHospStatus_my(@PathVariable String id,
@PathVariable Integer status){
//数据存在于mongodb中所以用repository操作
Boolean b = hospitalService.updateStatus_my(id,status);
if(b){
return Result.ok();
}else{
return Result.fail();
}
}
HospitalServiceImpl类实现:
//更新医院上线状态
@Override
public Boolean updateStatus_my(String id, Integer status) {
Hospital hospital = hospitalRepository.findById(id).get();
//System.out.println(hospital);
if(hospital != null){
hospital.setStatus(status);
hospital.setUpdateTime(new Date());
hospital.setIsDeleted(0);
hospitalRepository.save(hospital);//更新
return true;
}else{
return false;
}
}
swagger测试:
显示成功:
查看数据库status状态:状态改变成功:
//更新医院上线状态
@ApiOperation("更新医院上线状态")
@GetMapping("updateHospStatus/{id}/{status}")
public Result updateHospStatus(@PathVariable String id,
@PathVariable Integer status){
hospitalService.updateStatus(id,status);
return Result.ok();
}
课件老师的方法:
@Override // //更新医院上线状态
public void updateStatus(String id, Integer status) {
//根据id查询医院信息
Hospital hospital = hospitalRepository.findById(id).get();
//设置修改的值,本质就是修改医院status
hospital.setStatus(status);
hospital.setUpdateTime(new Date());
hospitalRepository.save(hospital);
}
更新医院状态的前端:
组件:
前端api接口:对应后端接口:
//更新医院上线状态
updateStatus(id,status) {
return request({
url: `/admin/hosp/hospital/updateHospStatus_my/${id}/${status}`,
method: 'put'
})
},
js方法:
//5.更新医院上线状态
updateStatus(id,status) {
hospApi.updateStatus(id,status).then( (response) => {
//刷新页面
this.fetchData(this.page);
});
}
页面测试:可以正常使用:
3、医院详情接口
3.1 api接口
后台接口测试:
3.2 医院详情前端
查看详情的按钮:
3.2.1添加隐藏路由
{
path: 'hospital/show/:id',
name: '查看',
component: () => import('@/views/hosp/show'),
meta: { title: '查看', noCache: true },
hidden: true
}
创建views/hosp/show.vue页面:
3.2.3封装api请求
//查看医院详情
getHospById(id) {
return request ({
url: `/admin/hosp/hospital/showHospDetail/${id}`,
method: 'get'
})
}
3.2.4 修改显示页面组件
添加/views/hosp/show.vue组件
<template>
<div class="app-container">
<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>
复制页面show组件
排班信息接口:
根据医院编号就可以查出此医院的所有科室信息:
科室结构: