是不是很好奇,好好的讲五大组件呢,怎么到Fegin了呢?还不是因为可以简化开发方便使用。
而且Hystrix也依赖了Fegin所以下一章将Hystrix之前了解下Fegin(奋)
Feign是一种声明式、模板化的HTTP客户端。
我们还是在原有的基础上进行修改啊,没有看前面章节的可以看一下,或者跟着步骤来也可以
(一)SpringCloud之服务发现——Netflix Eureka_馒头花卷儿的博客-CSDN博客SpringCloud之服务发现——Netflix Eurekahttps://blog.csdn.net/suxiexingchen/article/details/125153278(二)SpringCloud之负载均衡——Netflix Ribbon_馒头花卷儿的博客-CSDN博客SpringCloud之负载均衡——Netflix Ribbonhttps://blog.csdn.net/suxiexingchen/article/details/125247138
1.首先我们需要添加feign的依赖JAR包这里使用的是OpenFeign
Feign和OpenFeign的区别:org.springframework.cloud spring-cloud-starter-openfeign
- Feign是Springcloud组件中的一个轻量级Restful的HTTP服务客户端,Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务
- OpenFeign是springcloud在Feign的基础上支持了SpringMVC的注解,如@RequestMapping等等。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。
2.配置文件原封不动
eureka:
client:
serviceUrl: #注册中心的地址
defaultZone: http://localhost:8761/eureka/
server:
port: 8764 #服务端口号
spring:
application:
name: eureka-service-consumerA #提供者的服务名称
3.制作一个接口我们自己定义,通过这个接口我们去访问Rureka并转发到提供者的服务器
package com.studycloud.eurekaclientproducer;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient("eureka-service-provider")//eureka-service-provider是提供者的服务名称
public interface TestInterface {
@RequestMapping("/test")
public String test();
}
4.接着在写一个Controller类来访问函数
package com.studycloud.eurekaclientproducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
TestInterface testInterface;
@RequestMapping("/test")
public String test(){
String result = testInterface.test();
return result;
}
}
5.最后需要在启动类上加上@EnableFeignClients这个注解,否则要报错说找不到你刚才写的接口的
package com.studycloud.eurekaclientproducer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class EurekaClientProducerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientProducerApplication.class, args);
}
}
6.最后我启动所有服务,并访问查看结果是正常的
显而易见我得到了预期的效果,访问以轮询的方式进行访问了。
代码一定要去实际操作写一写,才能有自己的感受哦


