Feign實現RPC調用

前言

Feign的中文名稱翻譯過來是假裝
那麼Feign假裝的是什麼呢?答案很明確,Feign假裝的是服務提供者。
Feign能夠用來作什麼?既然能假裝,固然能提供服務提供者的功能,即RPC調用服務提供者功能。前端

1、構建Feign

step1
新建一個SpringBoot項目,導入web,feign,eureka client的pom依賴;這種依賴在各類IDE及SpringBoot構建網頁上都是直接輸入關鍵字按Enter就能夠的
git

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就能夠了github

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,即容許開啓Feignweb

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,方法名隨便起,參數要給人間傳過去spring

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便於前端觀察app

@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/springclouddom

相關文章
相關標籤/搜索