springcloud-fegin 组件调用
    		       		warning:
    		            这篇文章距离上次修改已过422天,其中的内容可能已经有所变动。
    		        
        		                
                Spring Cloud Feign 是一个声明式的Web服务客户端,它用注解的方式简化了Web服务的调用。
以下是一个使用Spring Cloud Feign的示例:
- 添加依赖到你的pom.xml:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>- 启动类上添加@EnableFeignClients注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
 
@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}- 创建一个Feign客户端接口:
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@FeignClient(name = "remote-service", url = "http://localhost:8080")
public interface RemoteServiceClient {
    @GetMapping("/service")
    String getService(@RequestParam(value = "param") String param);
}- 使用Feign客户端:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class Controller {
 
    @Autowired
    private RemoteServiceClient remoteServiceClient;
 
    @GetMapping("/call-service")
    public String callService(String param) {
        return remoteServiceClient.getService(param);
    }
}在这个例子中,RemoteServiceClient是一个Feign客户端接口,用来定义远程服务的调用。当你调用callService方法时,Feign会负责向http://localhost:8080/service发起请求,并将结果返回。
评论已关闭