Feign实现RPC调用 - Go语言中文社区

Feign实现RPC调用


前言

Feign的中文名称翻译过来是伪装
那么Feign伪装的是什么呢?答案很明确,Feign伪装的是服务提供者。
Feign可以用来做什么?既然能伪装,当然能提供服务提供者的功能,即RPC调用服务提供者功能。

一、构建Feign

step1
新建一个SpringBoot项目,导入web,feign,eureka client的pom依赖;这种依赖在各种IDE及SpringBoot构建网页上都是直接输入关键字按Enter就可以的

12062369-fff9888e90f1b8d4.png
image.png

step2
配置application.yml文件,还是用前两篇的Eureka server

eureka:
  client:
    serviceUrl:
      defaultZone: http://server1:20001/eureka/
server:
  port: 8766
spring:
  application:
    name: service-feign

step3
配置负载均衡策略,新建一个类,配置bean Irule就可以了

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LoadBalancerConfig {
    @Bean
    public IRule getRule() {
        return new RandomRule();
    }
}

step4
主类开启Feign注解@EnableFeignClients,即允许开启Feign

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class FeignApplication {

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

step5
关键步骤来了,创建一个伪服务提供者接口(不需要实现),你伪装谁@FeignClient的value就写谁的名字。调用哪个接口就在RequestMapping 的value标注那个接口的url,方法名随便起,参数要给人间传过去

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "service-hi")
public interface ServiceFeign {
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    String sayHi(@RequestParam(value = "name") String name);
}

step6
创建一个Controller便于前端观察

@RestController
public class FeignController {
    
    @Autowired
    private ServiceFeign serviceFeign;

    @GetMapping(value = "/hi")
    public String sayHi(@RequestParam String name) {
        return serviceFeign.sayHi(name);
    }
}

step7
启动eureka server,启动三个service-hi,启动service-feign,点击service-feign

12062369-ebf10d54bde32ad0.png
image.png

step8
输入url,多次刷新,发现确实是按照负载均衡的随机策略来的
12062369-6da83bc5bd5db0f9.png
image.png

总结

本篇git地址https://github.com/KouLouYiMaSi/springcloud

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/KouLouYiMaSi/article/details/82879852
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-09-04 14:11:46
  • 阅读 ( 2463 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

推荐文章

猜你喜欢