Feign:
- 声明式REST客户端(伪RPC)
- 采用了基于接口的注解
第一步:添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
第二步:添加注解
package com.example.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
第三步:定义调用的接口
package com.example.order.client;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* product:被调用的serverID
* /msg:被调用的接口名
* productMsg:自定义接口名
*
* @Author hy
* @Date 2018/12/25 15:26
**/
@FeignClient(name = "product")
public interface ProductClient {
@RequestMapping("/msg")
String productMsg();
}
第四步:使用
package com.example.order.controller;
import com.example.order.client.ProductClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ClientController {
/* @Autowired
private RestTemplate RestTemplate;
@RequestMapping("/getMsg")
public String getMsg(){
String msg = RestTemplate.getForObject("http://PRODUCT/msg",String.class);
return msg;
}*/
@Autowired
private ProductClient productClient;
@RequestMapping("/getMsg")
public String getMsg(){
String result = productClient.productMsg();
System.out.println(result);
return result;
}
}
第五步:启动测试:成功
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
网友评论