您的位置:首页 > 编程语言 > Java开发

SpringCloud入门(三):Feign声明式服务调用

2019-05-23 14:57 1546 查看

Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。Feign提供了HTTP请求的模板,通过编写简单的接口和插入注解,就可以定义好HTTP请求的参数、格式、地址等信息。Feign是用@FeignClient来映射服务。

Feign是客户端简化微服务调用的工具,因此我们只需要在客户端进行Feign的配置和服务调用,而服务提供端不需要做任何更改。

服务消费者cloudFeignConsumer:

POM文件:

[code]        <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</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-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

启动类:

[code]@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients (basePackages= {"cn.zsm.spring"})
@ComponentScan ("cn.zsm.spring")
public class CloudFeign {

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

}

启动类上有两个注解@EnableFeignClients和@ComponentScan,Feign是用接口和注解进行服务调用的,这两个注解用于扫描服务调用接口所在的包,在Spring容器中会注入接口对应的实例。

application.yml:

[code]server:
port: 8088

eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eurekaServer7001:7001/eureka/

Controller:

[code]@RestController
public class CloudFeignController {
@Autowired
private FeignService feignService;

@GetMapping("/Consumer/get/{message}")
public String getDept(@PathVariable("message") String message){
return this.feignService.get(message);
}
}

service接口:

[code]@FeignClient(value = "CLOUD-PROVIDER")
public interface FeignService {

@RequestMapping(value = "/provider/get/{message}", method = RequestMethod.GET)
String get(@PathVariable("message") String message);

}

service接口上有一个@FeignClient注解,用于进行服务调用配置:value属性用于指定调用的微服务名,接口中的方法上的注解@RequestMapping用于指定调用的微服务的方法和请求方式。至此使用Feign调用微服务的客户端请求创建完成。服务注册中心和服务提供者的创建与之前相同,这里不再赘述。

分别启动Eureka服务注册中心、服务提供者、和基于Feign实现的服务消费者,访问服务消费者:http://localhost:8088/Consumer/get/12345

相比于Ribbon+RestTemplate,Feign面向接口+注解调用微服务,实现起来更加简单。Feign也可以与Ribbon组合使用,进行一些自定义的负载均衡设置。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: