nacos微服务调用

2020-05-25  本文已影响0人  simplerandom

微服务工程依赖

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>parent</artifactId>
        <groupId>org.limakilo</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>consumer</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
</project>

application.yml文件

server:
  port: 10001
spring:
  application:
    name: consumer
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

# 开启服务无法成功调用时,调用fallback类对应的方法
feign:
  hystrix:
    enabled: true

自定义feign客户端()
调用hello方法会请求nacos-discovery-server服务对应的映射地址

package org.limakilo;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name="nacos-discovery-server",fallback = FeignError.class)
public interface ForeignClient {
    @GetMapping("/hello")
    String hello();
}

fallback类

package org.limakilo;

import org.springframework.stereotype.Component;

@Component
public class FeignError implements  ForeignClient {
    @Override
    public String hello() {
        return "10001异常";
    }
}

启动类+controller类

package org.limakilo;

import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@EnableFeignClients
@ResponseBody
@SpringBootApplication
@EnableDiscoveryClient
@Controller
public class ConsumerApplication {
    @Autowired
    ForeignClient foreignClient;

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

    @GetMapping("/hello")
    public String hello() {

        return foreignClient.hello();
    }
}

参考

上一篇下一篇

猜你喜欢

热点阅读