Spring Cloud学习笔记(五)Feign客户端

Feign是声明式WebService客户端,它让服务之间的调用变的更加简单。Feign默认底层使用的是ribbon客户端,所以具有负载均衡的功能,并且Feign整合了Hystrix,具备熔断的功能。

Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. 

基于上一节学习笔记的ribbon工程,在Consumer工程里POM里加入依赖文件:


	org.springframework.cloud
	spring-cloud-starter-openfeign

在启动类上加上@EnableFeignClients注解开启Feign的功能:

package org.dothwinds.serviceconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class SpringCloudStudyServiceConsumerApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringCloudStudyServiceConsumerApplication.class, args);
	}

	//注入restTemplate
	@Bean
	@LoadBalanced
	public RestTemplate getRestTemplate(){
		return new RestTemplate();
	}

}

指定一个接口,加上feign的注解,指定需要调用的服务及调用方式

package org.dothwinds.serviceconsumer.serviceinterface;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

//FeignClient需要调用的服务
@FeignClient("service-provider")
public interface ServiceConsumerInterface {

    @GetMapping(value = "/testLoadBalance")
    public String serviceCousumer();
}

在Controller里改写一下原来的方法测试一下我们feign的客户端是否好用

package org.dothwinds.serviceconsumer.controller;


import org.dothwinds.serviceconsumer.serviceinterface.ServiceConsumerInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ServiceConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ServiceConsumerInterface serviceConsumerInterface;

    @GetMapping("/testLoadBalance")
    public String serviceCousumer(){
//       return restTemplate.getForObject("http://SERVICE-PROVIDER/service", String.class);
        serviceConsumerInterface.serviceCousumer();
    }
}

接下来我们来测试一下,访问testLoadBalance,看一下是否有效果,重复刷新页面地址:

Spring Cloud学习笔记(五)Feign客户端_第1张图片

Spring Cloud学习笔记(五)Feign客户端_第2张图片

参考资料:

参考资料:https://cloud.spring.io/spring-cloud-static/Greenwich.SR5/single/spring-cloud.html

代码地址:https://gitee.com/dothwinds/Spring-Cloud-Study/tree/master/spring-cloud-study-ribbon

你可能感兴趣的:(Spring,Cloud,java,spring)