Feign实现负载均衡

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,多次刷新发现端口在不断改变。

 

转载于:https://www.cnblogs.com/SakerLiu/p/9744800.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值