springcloud+nacos+feign+gateway构建微服务

依赖版本

spring 5.3.27
springboot 2.7.12
springcloud 2021.0.5
spring-cloud-alibaba 2021.0.5.0
nacos-server 2.2.3
spring-cloud-starter-openfeign 3.1.5
spring-cloud-starter-gateway 3.1.4
jdk 1.8

工程目录

  • mirror-nacos
    • base-consumers-nacos
    • base-feign
    • base-gateway-nacos
    • base-provider-nacos

Nacos注册中心

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

下载安装包

在Nacos的GitHub页面,提供有下载链接,可以下载编译好的Nacos服务端或者源代码:

GitHub主页:https://github.com/alibaba/nacos

GitHub的Release下载页:https://github.com/alibaba/nacos/releases

访问GitHub的Release下载页即可

https://github.com/alibaba/nacos/releases/download/2.2.3/nacos-server-2.2.3.zip

https://github.com/alibaba/nacos/releases/download/2.2.3/nacos-server-2.2.3.tar.gz

linux解压命令

tar -xvf nacos-server-2.2.3.tar.gz

端口配置

Nacos的默认端口是8848,如果你电脑上的其它进程占用了8848端口,请先尝试关闭该进程。

如果无法关闭占用8848端口的进程,也可以进入nacos的conf目录,修改配置文件中的端口:

找到application.properties配置文件: 更改此处默认的端口8848

windows启动命令

进入到bin文件夹

startup.cmd -m standalone

linux启动命令

进入到bin文件夹

sh startup.sh -m standalone

访问地址

输入nacos访问地址:http://127.0.0.1:8848/nacos

默认用户名/密码:nacos/nacos

可在 Nacos 注册中心看到已注册的服务

Nacos的依赖

父工程:

 <properties>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <maven.compiler.compilerVersion>1.8maven.compiler.compilerVersion>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
    <spring.version>5.3.27spring.version>
    <spring-boot.version>2.7.12spring-boot.version>
    <spring-cloud.version>2021.0.5spring-cloud.version>
    <spring.cloud.alibaba.version>2021.0.5.0spring.cloud.alibaba.version>
properties>
<dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-dependenciesartifactId>
        <version>${spring-boot.version}version>
        <type>pomtype>
        <scope>importscope>
    dependency>
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-dependenciesartifactId>
        <version>${spring-cloud.version}version>
        <type>pomtype>
        <scope>importscope>
    dependency>
    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-alibaba-dependenciesartifactId>
        <version>${spring.cloud.alibaba.version}version>
        <type>pomtype>
        <scope>importscope>
    dependency>
dependencies>
dependencyManagement>

1、provider生产厂者工程

base-provider-nacos

<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-bootstrapartifactId>
dependency>
server:
  port: 7710
spring:
  application:
    name: base-provider-server
  cloud:
    nacos:
      discovery:
        ip: localhost
        server-addr: localhost:8848
      config:
        file-extension: yaml
        server-addr: localhost:8848

项目启动类添加注解:@EnableDiscoveryClient(注册中心注册发现)

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

定义测试接口

@RestController
public class EchoController {
    @GetMapping(value = "/echo/{str}")
    public String echo(@PathVariable String str) {
        return "Hello Nacos Discovery " + str;
}

启动生产者工程,访问地址测试接口是否通畅
http://localhost:7710/echo/test

2、Feign工程

Feign 是一个声明式 Web 服务客户端。它使编写 Web 服务客户端变得更加容易。只需要创建一个接口并添加注解就可以进行微服务的调用。

将provider工程中将需要对外提供服务的接口进行定义,定义接口地址、输入参数、输出参参数

  
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
        
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-netflix-hystrixartifactId>
    <version>2.2.10.RELEASEversion>
dependency>
        
<dependency>
    <groupId>io.github.openfeigngroupId>
    <artifactId>feign-httpclientartifactId>
    <version>11.0version>
dependency>
/*定义微服务名、项目访问前缀等常量*/
public class ApplicationNameConstant {
    public static final String SERVER_NAME = "base-provider-server";
    public static final String CONTENT_PATH = "";
}
/*定义对外提供服务的接口*/
@FeignClient(value = ApplicationNameConstant.SERVER_NAME, path = ApplicationNameConstant.CONTENT_PATH, fallbackFactory = DemoEchoFallback.class)
public interface DemoEchoFeign {
    @GetMapping("echo/{str}")
    String echo(@PathVariable(value = "str") String str);
}

/*熔断降级*/
@Component
@Slf4j
public class DemoEchoFallback implements FallbackFactory<DemoEchoFeign> {
    @Override
    public DemoEchoFeign create(Throwable cause) {
        log.error("异常原因:{}", cause.getMessage(), cause);
        return new DemoEchoFeign() {
            @Override
            public String echo(String str) {
                return "接口调用失败";
            }
        };
    }
}

3、consumers消费者工程

base-consumers-nacos

 <dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-bootstrapartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-loadbalancerartifactId>
dependency>

server:
  port: 7720
spring:
  application:
    name: base-consumers-nacos
  cloud:
    nacos:
      discovery:
        ip: localhost
        server-addr: localhost:8848
      config:
        file-extension: yaml
        server-addr: localhost:8848

项目启动类添加两个注解:@EnableDiscoveryClient(注册中心注册发现)、@EnableFeignClients(feign客户端调用)

@EnableFeignClients(basePackages = "com.dc.base.feign.*")
@EnableDiscoveryClient
@SpringBootApplication
public class NacosConsumersApp {
    public static void main(String[] args) {
        SpringApplication.run(NacosConsumersApp.class, args);
    }
}

consumers服务中引入feign工程,通过调用feign工程中定义的接口进行服务消费

@RestController
public class DemoEchoController {
    @Resource
    private DemoEchoFeign demoEchoFeign;

    @ApiOperation(value = "测试")
    @GetMapping("echo/{str}")
    public String echo(@PathVariable String str) {
        String res = "Consumer " + demoEchoFeign.echo(str);
        return res;
    }
}

启动消费者服务,测试接口是否通畅;验证通过后,关闭生产者服务,继续调用接口,验证是否能熔断降级

http://localhost:7720/echo/test

gateway网关工程

base-gateway-nacos

<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
dependency>
<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-bootstrapartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-loadbalancerartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-gatewayartifactId>
dependency>
server:
  port: 7730
spring:
  application:
    name: base-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      discovery:
        locator:
          enabled: true  #是否与服务注册于发现组件结合,通过 serviceId 转发到具体的服务
          lower-case-service-id: true
      routes:
        - id: gateway-service-provider
          uri: lb://base-provider-server
          predicates:
            - Path=/provider/**
          filters:
            - StripPrefix=1
        - id: gateway-service-consumer
          uri: lb://base-consumers-nacos
          predicates:
            - Path=/consumers/**
          filters:
            - StripPrefix=1
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

启动消费者服务,访问消费者工程和生产者工程,验证接口是否通畅

http://localhost:7730/provider/echo/test

http://localhost:7730/consumers/echo/test

你可能感兴趣的:(spring,cloud,gateway,微服务)