三个JAVA臭皮匠

Feign实现RPC调用

2018-08-02  本文已影响0人  后厂村老司机

前言

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

一、构建Feign

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

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

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

总结

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

上一篇 下一篇

猜你喜欢

热点阅读