SpringCloud(四):服务消费(Feign)

一、Feign介绍

Feign是一个声明式的伪Http客户端,它使得写Http客户端变得更简单。使用Feign,只需要创建一个接口并注解。它具有可插拔的注解特性,可使用Feign 注解和JAX-RS注解。Feign支持可插拔的编码器和解码器。Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。

二、Feign消费者

这里写图片描述

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客户端

package cn.saytime.service;


import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient("hello-service")
public interface HelloService {

    @RequestMapping("hello")
    String hello (@RequestParam(value = "name") String name) ;
}

注意点:这里hello-service大小写都可以,默认会转成大写

还有一点要注意

@RequestParam(value = "name")

这里必须是这样配置,如果不配置或者配置的value=name1或者是其他值,相当于传其他参数key过去,在这里传错的话,会返回hello, null,因为hello-service接口拿不到name的值。

启动类

package cn.saytime;

import cn.saytime.service.HelloService;
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;

@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);
	}
}

三、测试

同样的,先启动eureka-server:8001, 以及hello-service:8011,8012,然后访问:

http://localhost:8031/hello?name=feign

结果:

hello, feign

同样的多次访问,hello-service:8011,8012日志都有打印调用信息,表示也实现了负载均衡。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值