九、SpringCloud之Feign的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29479041/article/details/83856561

一、Feign简介

  • 声明式Rest客户端(伪RPC)
  • 采用基于接口的注解(定义接口,然后在接口上添加注解‘)

二、使用步骤

客户端:

@RestController
public class ServerController {
    @GetMapping("/msg")
    public String msg(){
        return "this is product msg";
    }
}

服务端:

  • 1.引入 Feign 依赖
                <!-- 引入feign 应用通信-->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
			<version>1.4.5.RELEASE</version>
		</dependency>
  • 2在启动的主类上加 @EnableFeignClients 注解
@EnableDiscoveryClient //开启服务发现功能
@SpringBootApplication
@EnableFeignClients//开启Feign功能
public class OrderApplication {
	public static void main(String[] args) {
		SpringApplication.run(OrderApplication.class, args);
	}
}
  • 3.声名调用哪个应用的哪个方法
/**
 * 调用客户端接口
 * */
@FeignClient(name="product") //name是指客户端的名字
public interface ProductClient {
    @GetMapping("/msg")//调用客户端的哪个方法
    String productMsg(); // 方法名可以不一样
}
  • 4.调用
@RestController
@Slf4j
public class ClientController {

    @Autowired
    private ProductClient productClient;
    @GetMapping("/getProductMsg")
    public String msg(){
        String response = productClient.productMsg();
        log.info("response={}",response);
        return response;
    }
}
  • 5.测试

测试地址:http://localhost:8866/getProductMsg

猜你喜欢

转载自blog.csdn.net/qq_29479041/article/details/83856561