Feign负载均衡

前言:Feign是一个声明式WebService客户端,使用方法时定义一个接口并在上面添加注解即可。Feign支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持SpringMVC和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。

添加pom依赖

<dependencies>
    <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>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        <version>2.2.6.RELEASE</version>
    </dependency>
</dependencies>

编写yml

server:
  port: 8086
eureka:
  client:
    register-with-eureka: false #是否注册自己
    fetch-registry: true #是否需要从Eureka Server获取服务信息,默认为true
    service-url:
      defaultZone:  http://localhost:7001/eureka/,http://localhost:7002/eureka

写启动类

@SpringBootApplication
@EnableEurekaClient #表示这是一个客户端
@EnableFeignClients #告诉框架扫描所有使用注解 @FeignClient 定义的 feign 客户端。

写controller

package cn.bdqn.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

@RestController
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/user/get/{id}")
    String getUserById(@PathVariable("id") int id){
        return userService.getUserById(id);
    }

}

写service

package cn.bdqn.service;

import cn.bdqn.config.RequestClass;
import cn.bdqn.service.impl.UserServiceImpl;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient(value = "CLOUD-EUREKA-SERVER") #CLOUD-EUREKA-SERVER你的微服务名
public interface UserService {

    @GetMapping("/user/get/{id}")
    RequestClass getUserById(@PathVariable("id") int id);

}

启动后访问,即会按照轮询的方式调用provider集群

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值