服务发现、注册-搭建Nacos服务

一、服务注册

可以参考:Nacos、Feign、Hystrix服务介绍安装、注册、启动、调用

完整的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <modules>
        <module>service</module>
        <module>common</module>
        <module>infrastructure</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.stu</groupId>
    <artifactId>edu_parent</artifactId>
    <packaging>pom</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>edu_parent</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <mybatis-plus.version>3.4.0</mybatis-plus.version>
        <velocity.version>2.0</velocity.version>
        <swagger.version>2.9.2</swagger.version>
        <aliyun.oss.version>3.1.0</aliyun.oss.version>
        <jodatime.version>2.10.6</jodatime.version>
        <commons-fileupload.version>1.3.1</commons-fileupload.version>
        <commons-io.version>2.6</commons-io.version>
        <commons-lang.version>3.9</commons-lang.version>
        <httpclient.version>4.5.1</httpclient.version>
        <jwt.version>0.9.1</jwt.version>
        <aliyun-java-sdk-core.version>4.3.3</aliyun-java-sdk-core.version>
        <aliyun-java-sdk-kms.version>2.10.1</aliyun-java-sdk-kms.version>
        <aliyun-java-sdk-vod.version>2.15.10</aliyun-java-sdk-vod.version>
        <aliyun-sdk-vod-upload.version>1.4.11</aliyun-sdk-vod-upload.version>
        <fastjson.version>1.2.28</fastjson.version>
        <gson.version>2.8.2</gson.version>
        <json.version>20170516</json.version>
        <commons-dbutils.version>1.6</commons-dbutils.version>
        <canal.client.version>1.1.4</canal.client.version>
        <docker.image.prefix>zx</docker.image.prefix>
        <alibaba.easyexcel.version>2.2.6</alibaba.easyexcel.version>
        <apache.xmlbeans.version>3.1.0</apache.xmlbeans.version>
        <cloud-alibaba.version>2.2.1.RELEASE</cloud-alibaba.version>
        <spring-cloud-starter-gateway>2.2.0.RELEASE</spring-cloud-starter-gateway>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!--Spring Cloud-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR8</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-alibaba-dependencies -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!--mybatis-plus 持久层-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis-plus.version}</version>
            </dependency>

            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <version>${mybatis-plus.version}</version>
            </dependency>

            <!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
                <version>${velocity.version}</version>
            </dependency>

            <!--swagger-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>${swagger.version}</version>
            </dependency>

            <!--swagger ui-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>${swagger.version}</version>
            </dependency>

            <!--aliyunOSS-->
            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <version>${aliyun.oss.version}</version>
            </dependency>

            <!--日期时间工具-->
            <dependency>
                <groupId>joda-time</groupId>
                <artifactId>joda-time</artifactId>
                <version>${jodatime.version}</version>
            </dependency>

            <!--文件上传-->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>${commons-fileupload.version}</version>
            </dependency>

            <!--commons-io-->
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>${commons-io.version}</version>
            </dependency>

            <!--commons-lang3-->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
                <version>${commons-lang.version}</version>
            </dependency>

            <!--httpclient-->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>${httpclient.version}</version>
            </dependency>

            <!-- JWT -->
            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt</artifactId>
                <version>${jwt.version}</version>
            </dependency>

            <!--aliyun-->
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-core</artifactId>
                <version>${aliyun-java-sdk-core.version}</version>
            </dependency>
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-kms</artifactId>
                <version>${aliyun-java-sdk-kms.version}</version>
            </dependency>
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-vod</artifactId>
                <version>${aliyun-java-sdk-vod.version}</version>
            </dependency>

            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-sdk-vod-upload</artifactId>
                <version>${aliyun-sdk-vod-upload.version}</version>
            </dependency>

            <!--            json-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>${fastjson.version}</version>
            </dependency>

            <dependency>
                <groupId>org.json</groupId>
                <artifactId>json</artifactId>
                <version>${json.version}</version>
            </dependency>

            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>${gson.version}</version>
            </dependency>

            <dependency>
                <groupId>commons-dbutils</groupId>
                <artifactId>commons-dbutils</artifactId>
                <version>${commons-dbutils.version}</version>
            </dependency>

            <dependency>
                <groupId>com.alibaba.otter</groupId>
                <artifactId>canal.client</artifactId>
                <version>${canal.client.version}</version>
            </dependency>

            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>easyexcel</artifactId>
                <version>${alibaba.easyexcel.version}</version>
            </dependency>

            <dependency>
                <groupId>org.apache.xmlbeans</groupId>
                <artifactId>xmlbeans</artifactId>
                <version>${apache.xmlbeans.version}</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

<!--    <build>-->
<!--        <plugins>-->
<!--            <plugin>-->
<!--                <groupId>org.springframework.boot</groupId>-->
<!--                <artifactId>spring-boot-maven-plugin</artifactId>-->
<!--            </plugin>-->
<!--        </plugins>-->
<!--    </build>-->

</project>

 

1、配置pom

配置Nacos客户端的pom依赖

<!--服务注册-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2、添加服务配置信息

配置application.yml,在客户端微服务中添加注册Nacos服务的配置信息,原来的服务名改为service-edu,不用下划线

spring:
  profiles:
    # 环境设置
    active: dev

  application:
    # 服务名
    name: service-edu
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

 

 

3、添加Nacos客户端注解

package com.stu.service.edu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@ComponentScan(basePackages = "com.stu")
public class ServiceEduApplication {

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

 

4、启动客户端微服务

启动注册中心

启动已注册的微服务,可以在Nacos服务列表中看到被注册的微服务

 

 

二、实现服务调用

1、需求

删除课时的同时删除云端视频

2、在service模块添加pom依赖

<!-- 服务调用 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

 

3、在调用端的启动类添加注解

@EnableFeignClients

创建client包

@FeignClient注解用于指定从哪个服务中调用功能 ,名称与被调用的服务名保持一致。

@GetMapping注解用于对被调用的微服务进行地址映射。

@PathVariable注解一定要指定参数名称,否则出错

@Component注解防止在其他位置注入VodClient时idea报错

package com.stu.service.edu.client;
import com.stu.service.base.result.R;
import com.stu.service.edu.client.fallback.VodFileDegradeFeignClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
//这个是vod属性文件里的服务名,即spring.application.name=service-vod,
//fallback是实现类的class
//@FeignClient(name="service-vod",fallback = VodFileDegradeFeignClient.class)
@FeignClient("service-vod")
@Component
public interface VodClient {

    //根据id删除阿里云视频(映射路径是Vod业务里controller层的类映射+方法上的映射,即
    // @RequestMapping("/admin/vod") +  @DeleteMapping("removeVideo/{id}")

    /* @FeignClient注解用于指定从哪个服务中调用功能 ,名称与被调用的服务名保持一致。
    @GetMapping 注解用于对被调用的微服务进行地址映射。
    @PathVariable 注解一定要指定参数名称,否则出错
    @Component注解防止,在其他位置注入VodClient时idea报错*/

    /***********************************
     * 用途说明:根据视频id删除单个云端视频
     * @param id
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    @DeleteMapping("/admin/vod/removeVideo/{id}")
    public R removeVideo(@PathVariable String id);

    /***********************************
     * 用途说明:根据视频id删除多个云端视频
     * @param videoIdList
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    //根据id批量删除阿里云视频
    @DeleteMapping("/admin/vod/removeVideoBatch")
    public R removeVideoBatch(@RequestParam("videoIdList") List<String> videoIdList);
}

5、调用微服务

在调用端的VideoServiceImpl中调用client中的方法

package com.stu.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stu.service.base.exception.CustomException;
import com.stu.service.base.result.R;
import com.stu.service.base.result.ResultCodeEnum;
import com.stu.service.edu.client.VodClient;
import com.stu.service.edu.entity.Video;
import com.stu.service.edu.mapper.VideoMapper;
import com.stu.service.edu.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author stu
 * @since 2022-05-08
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private VodClient vodClient;

    /***********************************
     * 用途说明:
     * @param courseId
     * 返回值说明:
     * @return boolean
     ***********************************/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeVideoByCourseId(String courseId) {
        //1根据课程id先删除小节
        //删除小节,需要删除对应的视频文件
        //1.根据课程id查询所有视频id
        QueryWrapper<Video> wrapperVidoe = new QueryWrapper();
        wrapperVidoe.eq("course_id", courseId);
        wrapperVidoe.select("video_source_id");//设置只查出video_source_id这一列
        List<Video> videoList = baseMapper.selectList(wrapperVidoe);
        //将List<Video>转换成List<String>
        List<String> idsList = null;
        if (null != videoList && videoList.size() > 0) {
            idsList = new ArrayList<>();
            for (Video vo : videoList) {
                if (!StringUtils.isEmpty(vo.getVideoSourceId())) {
                    idsList.add(vo.getVideoSourceId());
                }
            }
            if (null != idsList && idsList.size() > 0) {
                //删除阿里云的视频
                R result = vodClient.removeVideoBatch(idsList);

                //删除失败20001
                if (result.getCode() == 20001) {
                    throw new CustomException(ResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
                }
            }
        }

        /*baseMapper.deleteById(courseId);*/
        QueryWrapper<Video> wrapper = new QueryWrapper();
        wrapper.eq("course_id", courseId);
        return baseMapper.delete(wrapper) > 0;
    }

    /***********************************
     * 用途说明:删除云端视频和数据库的信息
     * @param id
     * 返回值说明:
     * @return boolean
     ***********************************/
    @Override
    public boolean removeVodAndVideoByCourseId(String id) {
        Video video = baseMapper.selectById(id);
        String videoSourceId = video.getVideoSourceId();

        if (StringUtils.isNotEmpty(videoSourceId)) {
            R result = vodClient.removeVideo(videoSourceId);
            //删除失败20001
            if (result.getCode() == 20001) {
                throw new CustomException(ResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
            }
        }

        return baseMapper.deleteById(id) > 0;
    }
}

 

三、feign结合Hystrix使用

1、在service的pom中添加依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
        <!--hystrix依赖,主要是用  @HystrixCommand -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

 

2、在配置文件中添加hystrix配置

#开启熔断机制
feign.hystrix.enabled=true
# 设置hystrix超时时间,默认1000ms
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000

3、在service-edu的client包里面创建熔断器的实现类

package com.stu.service.edu.client.fallback;

import com.stu.service.base.result.R;
import com.stu.service.edu.client.VodClient;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class  VodFileDegradeFeignClient  implements VodClient {

    /***********************************
     * 用途说明:根据视频id删除单个云端视频
     * @param id
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    @Override
    public R removeVideo(String id) {
        return R.error().message("删除视频出错了");
    }

    /***********************************
     * 用途说明:根据视频id删除多个云端视频
     * @param videoIdList
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    @Override
    public R removeVideoBatch(List<String> videoIdList) {
        return R.error().message("删除视频出错了");
    }
}

 

4、修改VodClient接口的注解

@FeignClient(name = "service-vod",fallback = VodClientFallback.class)

 

package com.stu.service.edu.client;
import com.stu.service.base.result.R;
import com.stu.service.edu.client.fallback.VodFileDegradeFeignClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
//这个是vod属性文件里的服务名,即spring.application.name=service-vod,
//fallback是实现类的class
@FeignClient(name="service-vod",fallback = VodFileDegradeFeignClient.class)
@Component
public interface VodClient {

    //根据id删除阿里云视频(映射路径是Vod业务里controller层的类映射+方法上的映射,即
    // @RequestMapping("/admin/vod") +  @DeleteMapping("removeVideo/{id}")

    /* @FeignClient注解用于指定从哪个服务中调用功能 ,名称与被调用的服务名保持一致。
    @GetMapping 注解用于对被调用的微服务进行地址映射。
    @PathVariable 注解一定要指定参数名称,否则出错
    @Component注解防止,在其他位置注入VodClient时idea报错*/

    /***********************************
     * 用途说明:根据视频id删除单个云端视频
     * @param id
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    @DeleteMapping("/admin/vod/removeVideo/{id}")
    public R removeVideo(@PathVariable String id);

    /***********************************
     * 用途说明:根据视频id删除多个云端视频
     * @param videoIdList
     * 返回值说明:
     * @return com.stu.service.base.result.R
     ***********************************/
    //根据id批量删除阿里云视频
    @DeleteMapping("/admin/vod/removeVideoBatch")
    public R removeVideoBatch(@RequestParam("videoIdList") List<String> videoIdList);
}

 

 

作者:
出处:https://www.cnblogs.com/konglxblog//
版权:本文版权归作者和博客园共有
转载:欢迎转载,文章中请给出原文连接,此文章仅为个人知识学习分享,否则必究法律责任

 

posted @ 2022-10-16 21:01  程序员小明1024  阅读(51)  评论(0编辑  收藏  举报