1. 本文在基于 Spring Cloud 做负载均衡文章上进行开发, 网址 https://www.cnblogs.com/SakerLiu/p/9743577.html, 首先创建一个 server,2 个端口不同的 service, 其中 server 的端口号为 8801,service 为 8802/8803
2. 按照创建 service 的方式新建一个 module, 命名为 my-feigns, 修改 pom 文件 server 为 client, 修改 application.properties 为 application.YAML, 在 pom.xml 文件中添加如下依赖
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
3. 在 application.YAML 添加如下内容
- eureka:
- client:
- serviceUrl:
- defaultZone: http://localhost:8801/eureka/
- server:
- port: 8811
- spring:
- application:
- name: my-feigns
4. 在主程序中添加 @EnableFeignClients 开启注解 Feign 功能, 添加 @EnableDiscoveryClient, 进行注册, 所得代码如下所示
- package com.example.myfeigns;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
- import org.springframework.cloud.openfeign.EnableFeignClients;
- @SpringBootApplication
- @EnableDiscoveryClient
- @EnableFeignClients
- public class MyFeignsApplication {
- public static void main(String[] args) {
- SpringApplication.run(MyFeignsApplication.class, args);
- }
- }
5. 在该包下新建一个 Hello 的接口和 Controller 文件, 并加入下述内容
- # 接口文件
- package com.example.myfeigns;
- 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("my-service")
- public interface SayHello {
- @RequestMapping(value = "/hi",method = RequestMethod.GET)
- String sayHi(@RequestParam(value = "name") String name);
- }
- #Controller 文件
- package com.example.myfeigns;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.Web.bind.annotation.RequestMapping;
- import org.springframework.Web.bind.annotation.RequestMethod;
- import org.springframework.Web.bind.annotation.RequestParam;
- import org.springframework.Web.bind.annotation.RestController;
- @RestController
- public class HelloController {
- @Autowired
- SayHello pp;
- @RequestMapping(value = "/hi",method = RequestMethod.GET)
- public String sayHi(@RequestParam String name){
- return pp.sayHi(name);
- }
- }
6. 运行主程序, 在网页中输入 http://localhost:8811/hi?name=lemon, 多次刷新发现端口在不断改变.
来源: http://www.bubuko.com/infodetail-2795432.html