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.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring.version>5.3.27</spring.version>
    <spring-boot.version>2.7.12</spring-boot.version>
    <spring-cloud.version>2021.0.5</spring-cloud.version>
    <spring.cloud.alibaba.version>2021.0.5.0</spring.cloud.alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${spring-boot.version}</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-alibaba-dependencies</artifactId>
        <version>${spring.cloud.alibaba.version}</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
</dependencies>
</dependencyManagement>

1、provider生产厂者工程

base-provider-nacos

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</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工程中将需要对外提供服务的接口进行定义,定义接口地址、输入参数、输出参参数

  <!--  添加springboot fegin依赖,product项目即可以作为生产者,又可以作为消费者-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
        <!--hystrix feign熔断降级-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.10.RELEASE</version>
</dependency>
        <!--feign发送参数超出限制修正-->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
    <version>11.0</version>
</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.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</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.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值