【Nacos学习】二、整合OpenFeign组件

功能实现

创建项目

创建【nacos-feign】子服务,用于测试OpenFeign组件的使用,其pom文件如下:



    4.0.0
    
        nacos
        com.kongcheng
        0.0.1-SNAPSHOT
    

    com.kongcheng
    nacos-feign
    0.0.1-SNAPSHOT
    nacos-feign
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.cloud
            spring-cloud-starter-alibaba-nacos-discovery
        
        
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
    

    
        
            
                org.springframework.boot
                2.3.0.RELEASE
                spring-boot-maven-plugin
            
        
    


主入口添加【@EnableDiscoveryClient】用作开启服务注册,【@EnableFeignClients】作为开启OpenFeign:

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

@SpringBootApplication
@EnableDiscoveryClient//开启服务注册
@EnableFeignClients//开启OpenFeign
public class NacosFeignApplication {

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

}

配置文件如下:

server:
  port: 18202
spring:
  application:
    name: nacos-feign
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848 # Nacos作为服务注册中心地址

定义远程接口

创建名为【api】的Package,如下所示:

【Nacos学习】二、整合OpenFeign组件_第1张图片

 创建RemoteClient接口,来定义OpenFeign要调用的远程服务接口:

调用的是前面创建的【nacos-provide】子服务中的方法,需要注意方法名需要与远程服务名相同

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

@FeignClient(name = "nacos-provide",fallback = RemoteHystrix.class)
public interface RemoteClient {

    @GetMapping("/helloNacos")
    String helloNacos();
}

创建RemoteHystrix接口,来进行熔断降级处理

import org.springframework.stereotype.Component;

/**
 * 服务降级处理
 */
@Component
public class RemoteHystrix implements RemoteClient{

    public String helloNacos() {
        return "请求超时了!";
    }
}

具体调用OpenFeign测试

创建【TestController】控制层:

import com.kongcheng.nacosfeign.api.RemoteClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private RemoteClient remoteClient;

    @GetMapping("/feign")
    public String test() {
        return remoteClient.helloNacos();
    }
}

完成后启动服务。

测试

需要启动【Nacos-server】,【nacos-provide】,【nacos-feign】,启动成功后浏览器访问:localhost:18202/feign,可以通过OpenFeign远程调用nacos-provide的接口

项目源码

https://gitee.com/dukeLiuyu/nacos

你可能感兴趣的:(Spring,Cloud,学习,java)