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

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

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

服务消费者cloudFeignConsumer:

POM文件:

        <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>

启动类:

@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:

server:
  port: 8088 

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

Controller:

@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接口:

@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组合使用,进行一些自定义的负载均衡设置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值