尚医通_第10章_后台医院管理模块

第10章_后台医院管理模块

文章目录

第一节.医院管理模块需求分析

一、医院管理系统

目前我们把医院、科室和排班都上传到了平台,那么管理平台就应该把他们管理起来,在我们的管理平台能够直观的查看这些信息

1、医院列表

在这里插入图片描述

2、医院详情

在这里插入图片描述

第二节.注册中心与服务调用

一、Nacos

1、基本概念

**(1)**Nacos 是阿里巴巴推出来的一个新开源项目,是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。

**(2)**常见的注册中心:

  1. Eureka(原生,2.0遇到性能瓶颈,停止维护)

  2. Zookeeper(支持,专业的独立产品。例如:dubbo)

  3. Consul(原生,GO语言开发)

  4. 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-discovery 实现服务的注册与发现。

**(3)**Nacos是以服务为主要服务对象的中间件,Nacos支持所有主流的服务发现、配置和管理。

Nacos主要提供以下四大功能:

    1. 服务发现和服务健康监测
    1. 动态配置服务
    1. 动态DNS服务
    1. 服务及其元数据管理

**(4)**Nacos结构图
在这里插入图片描述

2、Nacos下载和安装

(1)下载地址和版本

下载地址:https://github.com/alibaba/nacos/releases

下载版本:nacos-server-1.1.4.tar.gz或nacos-server-1.1.4.zip,解压任意目录即可

(2)启动nacos服务

- Linux/Unix/Mac

  • 启动命令(standalone代表着单机模式运行,非集群模式)

  • 启动命令:sh startup.sh -m standalone

- Windows

  • 启动命令:cmd startup.cmd 或者双击startup.cmd运行文件。

  • 访问:http://localhost:8848/nacos

  • 用户名密码:nacos/nacos

在这里插入图片描述

在这里插入图片描述

第二节.医院列表功能

一、医院列表功能(接口)

1、添加service分页接口与实现

(1)在HospitalService定义医院列表方法

/**
 * 分页查询
 * @param page 当前页码
 * @param limit 每页记录数
 * @param hospitalQueryVo 查询条件
*/
Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo);

(2)在HospitalServiceImpl添加医院列表实现的方法

@Override
public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
    Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
    //0为第一页
    Pageable pageable = PageRequest.of(page-1, limit, sort);
    Hospital hospital = new Hospital();
    BeanUtils.copyProperties(hospitalQueryVo, hospital);
    //创建匹配器,即如何使用查询条件
    ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
        .withIgnoreCase(true); //改变默认大小写忽略方式:忽略大小写
    //创建实例
    Example<Hospital> example = Example.of(hospital, matcher);
    Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
    return pages;
}

2、添加controller方法

在HospitalController添加医院列表方法

@Api(description = "医院接口")
@RestController
@RequestMapping("/admin/hosp/hospital")
@CrossOrigin
public class HospitalController {
    //注入service
    @Autowired
    private HospitalService hospitalService;
    @ApiOperation(value = "获取分页列表")
    @GetMapping("{page}/{limit}")
    public R index(@PathVariable Integer page, @PathVariable Integer limit, HospitalQueryVo hospitalQueryVo) {
        //调用方法
        return R.ok().data("pages",hospitalService.selectPage(page, limit, hospitalQueryVo));
    }
}

3、service_cmn模块提供接口

因为医院信息中包括医院等级信息,需要调用数据字典接口获取

3.1 添加service接口与实现

在DictService添加查询数据字典方法
/**
 * 根据上级编码与值获取数据字典名称
 * @param parentDictCode
* @param value
*/
String getNameByParentDictCodeAndValue(String parentDictCode, String value);DictServiceImpl实现查询数据字典方法
//实现方法
@Override
public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
    //如果value能唯一定位数据字典,parentDictCode可以传空,例如:省市区的value值能够唯一确定
    if(StringUtils.isEmpty(parentDictCode)) {
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
        if(null != dict) {
            return dict.getName();
        }
    } else {
        Dict parentDict = this.getDictByDictCode(parentDictCode);
        if(null == parentDict) return "";
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id",
                                                                     parentDict.getId()).eq("value", value));
        if(null != dict) {
            return dict.getName();
        }
    }
    return "";
}DictServiceImpl实现根据dict_code查询的方法
//实现方法 根据dict_code查询
private Dict getDictByDictCode(String dictCode) {
    QueryWrapper<Dict> wrapper = new QueryWrapper<>();
    wrapper.eq("dict_code",dictCode);
    Dict codeDict = baseMapper.selectOne(wrapper);
    return codeDict;
}

3.2 添加controller

在DictController添加方法

提供两个api接口,如省市区不需要上级编码,医院等级需要上级编码

@ApiOperation(value = "获取数据字典名称")
@GetMapping(value = "/getName/{parentDictCode}/{value}")
public String getName(
    @ApiParam(name = "parentDictCode", value = "上级编码", required = true)
    @PathVariable("parentDictCode") String parentDictCode,
    @ApiParam(name = "value", value = "值", required = true)
    @PathVariable("value") String value) {
    return dictService.getNameByParentDictCodeAndValue(parentDictCode, value);
}
@ApiOperation(value = "获取数据字典名称")
@GetMapping(value = "/getName/{value}")
public String getName(
    @ApiParam(name = "value", value = "值", required = true)
    @PathVariable("value") String value) {
    return dictService.getNameByParentDictCodeAndValue("", value);
}

4、封装Feign服务调用

4.1 搭建service_client父模块

在这里插入图片描述

4.2 在service_client模块引入依赖
<dependencies>
       <dependency>
            <groupId>com.atguigu</groupId>
            <artifactId>service_utils</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <scope>provided </scope>
        </dependency>
        <dependency>
            <groupId>com.atguigu</groupId>
            <artifactId>model</artifactId>
            <version>0.0.1-SNAPSHOT</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>

4.3 搭建service_cmn_client模块

在这里插入图片描述

4.4 添加Feign接口类

在这里插入图片描述

/**
 * 数据字典API接口
 */
@FeignClient("service-cmn")
public interface DictFeignClient {
    /**
     * 获取数据字典名称
     * @param parentDictCode
     * @param value
     * @return
     */
    @GetMapping(value = "/admin/cmn/dict/getName/{parentDictCode}/{value}")
    String getName(@PathVariable("parentDictCode") String parentDictCode, @PathVariable("value") String value);
    /**
     * 获取数据字典名称
     * @param value
     * @return
     */
    @GetMapping(value = "/admin/cmn/dict/getName/{value}")
    String getName(@PathVariable("value") String value);
}

5、医院接口远程调用数据字典

5.1 service模块引入依赖
<!-- 服务调用feign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
5.2 在service-hosp添加依赖
<dependency>
    <groupId>com.atguigu</groupId>
    <artifactId>service_cmn_client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>
5.3 service_hosp模块启动类添加注解
@SpringBootApplication
@ComponentScan(basePackages = {"com.atguigu"})
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.atguigu")
//可以保证当前模块能够扫描当前模块依赖的jar包中的FeignClient接口了
public class ServiceHospApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceHospApplication.class, args);
    }
}
5.4调整service方法

修改HospitalServiceImpl类实现分页

//注入远程调用数据字典
@Autowired
private DictFeignClient dictFeignClient;
@Override
public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
    Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
    //0为第一页
    Pageable pageable = PageRequest.of(page-1, limit, sort);
    Hospital hospital = new Hospital();
    BeanUtils.copyProperties(hospitalQueryVo, hospital);
    //创建匹配器,即如何使用查询条件
    ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式:模糊查询
        .withIgnoreCase(true); //改变默认大小写忽略方式:忽略大小写
    //创建实例
    Example<Hospital> example = Example.of(hospital, matcher);
    Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
    //封装医院等级数据
    pages.getContent().stream().forEach(item -> {
        this.packHospital(item);
    });
    return pages;
}
/**
     * 封装数据
     * @param hospital
     * @return
     */
private Hospital packHospital(Hospital hospital) {
    String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(),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 + hospital.getAddress());
    return hospital;
}
5.4 启动service_cmn和servvice_hosp服务,访问service_hosp的swagger-ui界面测试

6、添加数据字典显示接口

用于页面条件查询,多级联动

6.1 根据dicode查询下层节点

(1)添加controller

@ApiOperation(value = "根据dictCode获取下级节点")
@GetMapping(value = "/findByDictCode/{dictCode}")
public R findByDictCode(
    @ApiParam(name = "dictCode", value = "节点编码", required = true)
    @PathVariable String dictCode) {
    List<Dict> list = dictService.findByDictCode(dictCode);
    return R.ok().data("list",list);
}

(2)编写service

定义方法

List<Dict> findByDictCode(String dictCode);

实现方法

@Override
public List<Dict> findByDictCode(String dictCode) {
    Dict codeDict = this.getDictByDictCode(dictCode);
    if(null == codeDict) return null;
    return this.findDataChild(codeDict.getId());
}

第三节.医院列表功能(前端)

一、医院列表功能(前端)

1、添加医院列表路由

(1)在router/index.js添加
{
    path: 'hospital/list',
    name: '医院列表',
    component: () =>import('@/views/hosp/list'),
    meta: { title: '医院列表', icon: 'table' }
} 
(2)封装api请求

在api/yygh目录下创建hosp.js文件

在这里插入图片描述

import request from '@/utils/request'
export default {
  //医院列表
  getPageList(current,limit,searchObj) {
    return request ({
      url: `/admin/hosp/hospital/${current}/${limit}`,
      method: 'get',
      params: searchObj  
    })
  },
  //查询dictCode查询下级数据字典
  findByDictCode(dictCode) {
    return request({
        url: `/admin/cmn/dict/findByDictCode/${dictCode}`,
        method: 'get'
      })
    },
  
  //根据id查询下级数据字典
  findByParentId(dictCode) {
    return request({
        url: `/admin/cmn/dict/findChildData/${dictCode}`,
        method: 'get'
      })
  }
}
(3)创建hosp/list.vue页面

在这里插入图片描述

(4)编写页面内容

在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="请选择市">
                <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">
            <template slot-scope="scope">
                <router-link :to="'/hospSet/hospital/show/'+scope.row.id">
                    <el-button type="primary" size="mini">查看</el-button>
                </router-link>
                <router-link :to="'/hospSet/hospital/schedule/'+scope.row.hoscode">
                    <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>
    </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/yygh/hosp'
export default {
    data() {
        return {
            listLoading: true, // 数据是否正在加载
            list: null, // 医院列表数据集合
            total: 0, // 数据库中的总记录数
            page: 1, // 默认页码
            limit: 10, // 每页记录数
            searchObj: {
                provinceCode:'',
                cityCode:''
            }, // 查询表单对象
            provinceList: [], //所有省集合
            cityList: []   //所有市集合
        }
    },
    created() {
        //调用医院列表
        this.fetchData()
        //调用查询所有省的方法
        hospApi.findByDictCode('Province').then(response => {
            
            this.provinceList = response.data.list
        })
    },
    methods: {
        //医院列表
        fetchData(page=1) {
            this.page = page
            hospApi.getPageList(this.page,this.limit,this.searchObj)
                .then(response => {
                    //每页数据集合
                    this.list = response.data.pages.content
                    //总记录数
                    this.total = response.data.pages.totalElements
                    //加载图表不显示
                    this.listLoading = false
                })
        },
        //查询所有省
        findAllProvince() {
            hospApi.findByDictCode('Province')
                .then(response => {
                    this.provinceList = response.data.list
                })
        },
        //点击某个省,显示里面市(联动)
        provinceChanged() {
            //初始化值
            this.cityList = []
            this.searchObj.cityCode = ''
            //调用方法,根据省id,查询下面子节点
            hospApi.findByParentId(this.searchObj.provinceCode)
                .then(response => {
                    console.log(response.data.dictList)
                    this.cityList = response.data.dictList
                })
        },
        //分页,页码变化
        changeSize() {
            this.limit = size
            this.fetchData(1)
        }
    }
}
</script>

第四节.更新医院上线状态功能

一、更新医院状态(接口)

1、添加service方法和实现

(1)在HospService定义方法

void updateStatus(String id, Integer status);

(2)在HospServiceImpl实现方法

@Override
public void updateStatus(String id, Integer status) {
    if(status.intValue() == 0 || status.intValue() == 1) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }
}
2、添加controller

在HospController添加方法

@ApiOperation(value = "更新上线状态")
@GetMapping("updateStatus/{id}/{status}")
public R lock(
    @ApiParam(name = "id", value = "医院id", required = true)
    @PathVariable("id") String id,
    @ApiParam(name = "status", value = "状态(0:未上线 1:已上线)", required = true)
    @PathVariable("status") Integer status){
    hospitalService.updateStatus(id, status);
    return R.ok();
}

二、更新医院状态(前端)

1、封装api请求

在api/yygh/hosp.js添加

updateStatus(id, status) {
    return request({
        url: `/admin/hosp/hospital/updateStatus/${id}/${status}`,
        method: 'get'
    })
}

2、修改/views/hosp/list.vue组件

<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>
        <router-link :to="'/hospSet/hospital/schedule/'+scope.row.hoscode">
            <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>

添加调用方法

updateStatus(id, status) {
    hospApi.updateStatus(id, status)
        .then(response => {
        this.fetchData(this.page)
    })
},

第五节.医院详情功能

一、医院详情(接口)

1、添加service方法和实现

(1)在HospService定义方法

/**
     * 医院详情
     * @param id
     * @return
     */
Map<String, Object> show(String id);

(2)在HospServiceImpl定义方法

@Override
public Map<String, Object> show(String id) {
    Map<String, Object> result = new HashMap<>();
    Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
    //医院基本信息(包含医院等级)
    result.put("hospital",hospital);
    //单独处理更直观
    result.put("bookingRule", hospital.getBookingRule());
    //不需要重复返回
    hospital.setBookingRule(null);
    return result;
}
2、添加controller方法
@ApiOperation(value = "获取医院详情")
@GetMapping("show/{id}")
public R show(
    @ApiParam(name = "id", value = "医院id", required = true)
    @PathVariable String id) {
    return R.ok().data("hospital",hospitalService.show(id));
}

二、医院详情(前端)

1、添加隐藏路由

在router/index.js添加

{
  path: 'hospital/show/:id',
  name: '查看',
  component: () => import('@/views/hosp/show'),
  meta: { title: '查看', noCache: true },
  hidden: true
}
2、创建医院详情页面

加粗样式
**
(1)添加查看按钮

<router-link :to="'/hosp/hospital/show/'+scope.row.id">
    <el-button type="primary" size="mini">查看</el-button>
</router-link>

(2)封装api请求

//查看医院详情
getHospById(id) {
  return request ({
    url: `/admin/hosp/hospital/show/${id}`,
    method: 'get'
  })
}

(3)修改显示页面组件

<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/yygh/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.hospital
                    this.bookingRule = response.data.hospital.bookingRule
                })
        },
        //返回医院列表
        back() {
            this.$router.push({ path: '/hospSet/hosp/list' })
        }
    }
}
</script>

(4)引入样式

第一、将show.css文件复制到src/styles目录

在这里插入图片描述

第二、在src/main.js文件添加引用

import '@/styles/show.css'

第六节.Spring Cloud GateWay网关

一、网关基本概念

1、API网关介绍

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,其不仅提供统一的路由方式,并且还基于Filter链的方式提供了网关基本的功能,例如:安全、监控/埋点、限流等。

在这里插入图片描述

3、Spring Cloud Gateway核心概念

网关提供API全托管服务,丰富的API管理功能,辅助企业管理大规模的API,以降低管理成本和安全风险,包括协议适配、协议转发、安全策略、防刷、流量、监控日志等贡呢。一般来说网关对外暴露的URL或者接口信息,我们统称为路由信息。如果研发过网关中间件或者使用过Zuul的人,会知道网关的核心是Filter以及Filter Chain(Filter责任链)。Sprig Cloud Gateway也具有路由和Filter的概念。下面介绍一下Spring Cloud Gateway中几个重要的概念。

**(1)路由。**路由是网关最基础的部分,路由信息有一个ID、一个目的URL、一组断言和一组Filter组成。如果断言路由为真,则说明请求的URL和配置匹配

(2)断言。Java8中的断言函数。Spring Cloud Gateway中的断言函数输入类型是Spring5.0框架中的ServerWebExchange。Spring Cloud Gateway中的断言函数允许开发者去定义匹配来自于http request中的任何信息,比如请求头和参数等。

(3)过滤器。一个标准的Spring webFilter。Spring cloud gateway中的filter分为两种类型的Filter,分别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理

在这里插入图片描述

如图所示,Spring cloud Gateway发出请求。然后再由Gateway Handler Mapping中找到与请求相匹配的路由,将其发送到Gateway web handler。Handler再通过指定的过滤器链将请求发送到实际的服务执行业务逻辑,然后返回。

二、创建service_gateway模块(网关服务)

1、创建service_gateway模块
在这里插入图片描述

2、在pom.xml引入依赖

<dependencies>
     <dependency>
            <groupId>com.atguigu</groupId>
            <artifactId>service_utils</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、编写application.properties配置文件

# 服务端口
server.port=8222
# 服务名
spring.application.name=service-gateway
# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1: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/**

yml文件:

server:
  port: 8222
spring:
  application:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
      - id: SERVICE-HOSP
        uri: lb://SERVICE-HOSP
        predicates:
        - Path=/*/hosp/** # 路径匹配
      - id: SERVICE-CMN
        uri: lb://SERVICE-CMN
        predicates:
        - Path=/*/cmn/** # 路径匹配
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

4、编写启动类

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

二、网关相关配置

1、网关解决跨域问题

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

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

(1)创建配置类

在这里插入图片描述

@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标签的去掉,防止程序异常

2、全局Filter

统一处理会员登录与外部不允许访问的服务

import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
 * <p>
 * 全局Filter,统一处理会员登录与外部不允许访问的服务
 * </p>
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //api接口,校验必须登录
        if(antPathMatcher.match("/testuser/**/auth/**", path)) {
            List<String> tokenList = request.getHeaders().get("token");
            if(null == tokenList) {
                ServerHttpResponse response = exchange.getResponse();
                return out(response);
            } else {
//                Boolean isCheck = JwtUtils.checkToken(tokenList.get(0));
//                if(!isCheck) {
                    ServerHttpResponse response = exchange.getResponse();
                    return out(response);
//                }
            }
        }
        //内部服务接口,不允许外部访问
        if(antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            return out(response);
        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return 0;
    }
    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码,否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
3、自定义异常处理

服务网关调用服务时可能会有一些异常或服务不可用,它返回错误信息不友好,需要我们覆盖处理**ErrorHandlerConfig:**

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;
import java.util.Collections;
import java.util.List;
/**
 * 覆盖默认的异常处理
 *
 */
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfig {
    private final ServerProperties serverProperties;
    private final ApplicationContext applicationContext;
    private final ResourceProperties resourceProperties;
    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;
    public ErrorHandlerConfig(ServerProperties serverProperties,
                                     ResourceProperties resourceProperties,
                                     ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                        ServerCodecConfigurer serverCodecConfigurer,
                                     ApplicationContext applicationContext) {
        this.serverProperties = serverProperties;
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {
        JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(
                errorAttributes,
                this.resourceProperties,
                this.serverProperties.getError(),
                this.applicationContext);
        exceptionHandler.setViewResolvers(this.viewResolvers);
        exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }
}

*JsonExceptionHandler:*

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;
import java.util.HashMap;
import java.util.Map;
/**
 * 自定义异常处理
 *
 * <p>异常时用JSON代替HTML异常信息<p>
 *
 */
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {
    public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
                                ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }
    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("code", 20005);
        map.put("message", "网关失败");
        map.put("data", null);
        return map;
    }
    /**
     * 指定响应处理方法为JSON处理的方法
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
            }
    /**
     * 根据code获取对应的HttpStatus
     * @param errorAttributes
     */
    @Override
    protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
        return HttpStatus.OK;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

管程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值