feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。
在springcloud中不仅可以使用Ribbo进行负载均衡,也可以使用Feign。Feign是在Ribbon的基础上进行了一次改进,采用接口的方式实现负载均衡。
org.springframework.cloud spring-cloud-starter-openfeign
@FeignClient(value = "PROVIDER-NAME")声明这是一个FeignClient,value指明需要的服务id
@FeignClient(value = "PROVIDER-NAME") public interface DeptClientService { // 请求的路径需与服务提供者的路径一致 @RequestMapping(value = "/dev/add") boolean add(Dept dept); @RequestMapping(value = "/dev/{id}") Dept queryByID(@PathVariable("id") Long id ); @PostMapping(value = "/dev/list") ListqueryAll(); }
我们不再使用RestTemplate来获取所需的对象,而是通过之前定义的接口来获取
@RestController public class ConsumerController { @Autowired private DeptClientService service; @RequestMapping("/consumer/get/{id}") public Dept getByID(@PathVariable("id") Long id){ return this.service.queryByID(id); } @RequestMapping("/consumer/add") public boolean add(String dname){ Dept dept = new Dept(); dept.setDname(dname); return this.service.add(dept); } @RequestMapping("/consumer/list") public Listlist(){ return this.service.queryAll(); } }
@EnableFeignClients 开启Feign负载均衡
@SpringBootApplication(scanBasePackages = "com") @EnableEurekaClient @EnableFeignClients(basePackages = "com.service") public class FeignApplication { public static void main(String[] args) { SpringApplication.run(FeignApplication.class,args); } }
Ribbon
public class ConsumerController { @Autowired private RestTemplate template; private static final String url="http://PROVIDER-NAME"; @RequestMapping("/consumer/get/{id}") public Dept getByID(@PathVariable long id){ //请求的路径,返回的对象 Dept getEntity = template.getForObject(url + "/dev/" + id, Dept.class); return getEntity; } @RequestMapping("/consumer/add") public boolean add(String dname){ Dept dept = new Dept(); dept.setDname(dname); System.out.println(dept); //请求的路径,传递的参数,返回的对象 return template.postForObject(url+ "/dev/add",dept,Boolean.class); } @RequestMapping("/consumer/list") public Listlist(){ //请求的路径,返回的对象 return template.postForObject(url+"/dev/list",void.class,List.class); } }
Feign
@RestController public class ConsumerController { @Autowired private DeptClientService service; @RequestMapping("/consumer/get/{id}") public Dept getByID(@PathVariable("id") Long id){ return this.service.queryByID(id); } @RequestMapping("/consumer/add") public boolean add(String dname){ Dept dept = new Dept(); dept.setDname(dname); return this.service.add(dept); } @RequestMapping("/consumer/list") public Listlist(){ return this.service.queryAll(); } }
Feign的使用与Ribbon不同的地方在于
以上就是SpringCloud Feign的使用简介的详细内容,更多关于SpringCloud Feign的资料请关注其它相关文章!