Eureka + Ribbon + Feign 负载均衡

Step 5-1:使用 Spring Initializr 创建 Spring Boot 项目

选择如下配置

         

注:不熟悉如何搭建Spring Boot 项目,请点击

 

Step 5-2:创建配置文件 application.yml,内容如下

                                                                   

server:
  port: 8765
spring:
  application:
    name: service-feign

#如果没有eureka下边配置不用写
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

 

Step 5-3:编写启动类 @EnableDiscoveryClient

    注意:通过@EnableDiscoveryClient向服务中心注册;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignApplication {

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

}

 Step 5-4:编写 interface - SchedualServiceHi.java

package com.learn.feign.clients;

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 SchedualServiceHi {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}

  

Step 5-5:编写Contorller @RestController

import com.learn.feign.clients.SchedualServiceHi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HiController {


    //编译器报错,无视。 因为这个Bean是在程序启动的时候注入的,编译器感知不到,所以报错。
    @Autowired
    SchedualServiceHi schedualServiceHi;

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

启动后效果:访问 http://localhost:8765/hi?name=forezp                           

浏览器交替显示:

hi forezp,i am from port:8762

hi forezp,i am from port:8763

posted @ 2019-08-09 18:45  随风落木  阅读(13)  评论(0)    收藏  举报  来源