Feign是简化Java HTTP客户端开发的工具(java-to-httpclient-binder),它的灵感来自于Retrofit、JAXRS-2.0和WebSocket。Feign的初衷是降低统一绑定Denominator到HTTP API的复杂度,不区分是否为restful。
我们现在在问答微服务调用基础微服务的方法(根据ID查询标签)
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
@EnableEurekaClient
@EnableDiscoveryClient
package com.tensquare.qa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import util.IdWorker;
import util.JwtUtil;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class QaApplication {
public static void main(String[] args) {
SpringApplication.run(QaApplication.class, args);
}
@Bean
public IdWorker idWorkker(){
return new IdWorker(1, 1);
}
@Bean
public JwtUtil jwtUtil(){
return new JwtUtil();
}
}
package com.tensquare.qa.client;
import com.tensquare.qa.client.impl.BaseClientImpl;
import entity.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(value = "tensquare-base")
public interface BaseClient {
@RequestMapping(value = "/label/{labelId}", method = RequestMethod.GET)
public Result findById(@PathVariable("labelId") String labelId);
}
说明:
1)@FeignClient注解用于指定从哪个服务中调用功能 ,注意里面的名称与被调用的服务名保持一致,并且不能包含下划线。
2)@RequestMapping注解用于对被调用的微服务进行地址映射。注意 @PathVariable注解一定要指定参数名称,否则出错
@Autowired
private BaseClient baseClient;
@RequestMapping(value = "/label/{labelId}", method = RequestMethod.GET)
public Result findByLabelId(@PathVariable String labelId){
Result result = baseClient.findById(labelId);
return result;
}
http://192.168.2.10:9003/problem/label/1 能看到标签的信息
{"flag":true,"code":20000,"message":"查询成功","data":{"id":"1","labelname":"java","state":"1","count":null,"fans":null,"recommend":null}}
测试:同时开启多个基础微服务,看是否是轮流调用。
修改tensquare_base工程LabelController的findById方法
@RequestMapping(value = "/{labelId}", method = RequestMethod.GET)
public Result findById(@PathVariable("labelId") String id){
System.out.println("NO.1");
Label label = labelService.findById(id);
return new Result(true,StatusCode.OK, "查询成功", label);
}
启动基础微服务后,修改端口和输出信息,再次启动基础微服务
启动问答微服务,浏览器执行http://192.168.2.10:9003/problem/label/1 看是否轮流启动。