A, Feign introduce
Feign is a pseudo Http client a declarative, it makes writing easier Http client. Using Feign, only you need to create an interface and annotation. It has pluggable annotation feature can be used Feign JAX-RS annotations and notes. Feign pluggable encoder and decoder. Feign default integrated Ribbon, and Eureka and combined, the default implementation of load balancing.
Two, Feign consumer services:
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
application.properties:
spring.application.name=hello-consumer-feign server.port=8031 eureka.client.serviceUrl.defaultZone=http://localhost:8001/eureka/
Feign client: Package Penalty for cn.demo.service;
Import org.springframework.cloud.netflix.feign.FeignClient; Import org.springframework.web.bind.annotation.RequestMapping; Import org.springframework.web.bind.annotation.RequestParam;
// NOTE point: Case where user-service can, by default will be transferred to uppercase @FeignClient ( "the User-Service" ) public interface the HelloService {
// here must be configured such that, if not configured or configured value = name1 or other value, equivalent to pass other key parameters in the past here pass wrong, it will return hello, null, because the value of hello-service interface to get the name. @RequestMapping ( "Hello" ) String Hello (@RequestParam (value = "name" ) String name);
}
Start categories:
package cn.demo; import org.springframework.beans.factory.annotation.Autowired; 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; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import cn.demo.service.HelloService; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients @RestController public class HelloConsumerFeignApplication { public static void main(String[] args) { SpringApplication.run(HelloConsumerFeignApplication.class, args); } @Autowired private HelloService helloService; @RequestMapping("hello") public String hello(String name){ return helloService.hello(name); } }
Third, the test
Similarly, the first start eureka-server: 8001, and hello-service: 8011,8012, then visit:
http://localhost:8031/hello?name=feign
result:
The same number of visits, hello-service: 8011, 8012 print call log has information indicating also realizes load balancing.