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.yml,在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.yml添加如下内容
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,多次刷新发现端口在不断改变。