springcloud--feign

版权声明:本文为博主原创文章,未经博主允许不得转载。否则切鸡鸡~~ https://blog.csdn.net/kang5789/article/details/83023419

springcloud的服务调用框架有很多,比如Ribbon、RestTemplate、Feign,我选择Feign,因为它最简单

源码下载

maven依赖

启动类加两个注解

@EnableDiscoveryClient:在注册中心注入此服务(与@EnableEurekaClient区别是它在spring-cloud-commons中适用于所有的注册中心都通用,而@EnableEurekaClient只适用于euraka)
@EnableFeignClients:扫描被@FeignClient注解接口

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.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class EurekaFeign1Application {

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

配置

spring.application.name=eureka-feign
server.port=3001

eureka.client.serviceUrl.defaultZone=http://www.eureka1.com:1001/eureka,http://www.eureka2.com:1002/eureka

启动项目

首先在两个服务提供者写个方法,加个标识方便区分调用的那个提供者

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	@RequestMapping("hello")
	public String sayHello() {
		return "client1....hello";
	}
}

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	@RequestMapping("hello")
	public String sayHello() {
		return "client2....hello";
	}
}

写feign的调用,很简单

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

@FeignClient(value="eureka-client")
public interface HelloService {

	@RequestMapping("hello")
	String sayHello();
}

@FeignClient(value="eureka-client")   value表示调用名称为eureka-client服务提供者

@RequestMapping("hello")表示调用提供者的hello方法
写完了,复制一份项目,改下端口,就完成了feign服务消费者的高可用

重启项目postman测试一下,发两次请求可以看到轮循调用了服务提供者

猜你喜欢

转载自blog.csdn.net/kang5789/article/details/83023419