Feign:
Feign 是一个声明web服务客户端,这便得编写web服务客户端更容易,使用Feign 创建一个接口并对它进行注解,它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器,Spring Cloud 增加了对 Spring MVC的注解,Spring Web 默认使用了HttpMessageConverters, Spring Cloud 集成 Ribbon 和 Eureka 提供的负载均衡的HTTP客户端 Feign.
准备工作
准备工作和上一讲一样,启动eureka-server 和 eureka-server-client,同时更换eureka-server-client的配置文件中的端口号为8763,如下,再启动一个client。
搭建项目
新建一个项目
pom文件新增:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
配置文件:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8768
spring:
application:
name: service-feign-eric
启动类:
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 ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
服务类:定义一个feign接口,通过@ FeignClient(“服务名”),来指定调用哪个服务。比如在代码中调用了EUREKA-SERVER-CLIENT1服务的“/hi”接口,代码如下:
package cn.eric.springcloud.service;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value="EUREKA-SERVER-CLIENT1")
public interface SchedualServiceHi {
@RequestMapping(value="/hi",method = RequestMethod.GET)
String sayHiFromClientOne(@RequestParam(value="name") String name);
}
对外接口类:
package cn.eric.springcloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import cn.eric.springcloud.service.SchedualServiceHi;
@RestController
public class HelloController {
@Autowired
private SchedualServiceHi schedualServiceHi;
@RequestMapping(value = "/hiFeign",method = RequestMethod.GET)
public String sayHiFeign(@RequestParam String name){
return schedualServiceHi.sayHiFromClientOne(name);
}
}
运行启动类:
启动程序,多次访问http://localhost:8765/hi?name=forezp,浏览器交替显示:
hi eric,i am from port:8763
hi eric,i am from port:8762