3、Nacos结合openfeign

迷人的老约翰 2021-08-05 15:34:30 18546 0 0 0

####创建生产者producer

依赖

 <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2.1.0.RELEASE</version>
            <type> pom </type>
            <scope> import </scope>
        </dependency>
        <dependency>
            <groupId> com.alibaba.cloud </groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>

yml依赖

server:
  port: 9002
spring:
  application:
    name: nacos-producer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

类控制器

 @PostMapping("getJohn")
    public String getJohn(){
        return "这里是约翰";
    }

创建消费者consumer

依赖:

在nacos中使用openfeign 的时候需要导入loadbalanc包,但是nacos的ribbon会使loadbalanc失效,所以需要将nacos的ribbon失效,才能正常使用openfeign

openfeign调用

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
		<!-- 添加loadbalanc ->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2.1.0.RELEASE</version>
            <type> pom </type>
            <scope> import </scope>
        </dependency>
		<!-- 去除ribbon ->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.1.0.RELEASE</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

yml依赖

server:
  port: 9003
spring:
  application:
    name: nacos-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 
    compatibility-verifier:
      enabled: false

主类:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumerApplication {

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

}

业务层

@FeignClient(value = "nacos-producer")
public interface ProService {

    @PostMapping("/getJohn")
    public String getJohn();

}

类控制器

@RestController
public class Comsumer {

    @Resource
    private ProService proService;

    @PostMapping("/getJohn")
    public String getJohn(){
        return proService.getJohn();
    }

}

图片alt

图片alt

RestTemplate请求与之前使用的springcloud一致