spring cloud快速入门教程(六)进程间调用和微服务负载均衡(Feign)

本文介绍了Spring Cloud中Feign的使用,通过对比RestTemplate的简单性,展示Feign在进程间调用的便捷性。在示例中,通过复用userService模块调用productService微服务的getProduct接口,添加Feign依赖,并在Main.java中启用Feign客户端配置。实验证明,Feign能够成功实现微服务间的负载均衡并返回正确结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RestTemplate是不是很简单粗暴呢?还有更粗暴的,那就是Feign,很多人都用过Dubbo,Feign的用法跟他类似。

我们复用userService那个module去调用productService微服务中的getProduct接口,引入Feign的依赖包:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
在userService中创建一个接口,接口中要创建一个和微服务中要调用方法同名的方法,如下:

package com.tzy.userService;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient(value = "service-product")
public interface GetProductInterface {
    @RequestMapping(value = "/getProduct")
    String getProduct();
}
@FeignClient里的value指向要调用的微服务

@RequestMapping指向要远程调用的方法

另外要在启动程序Main.java里的类上加上@EnableFeignClients,表示为服务中要使用FeignClient。

package com.tzy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class Main {
    public static void main(String[] args){
        SpringApplication.run(Main.class,args);
    }
}
写一个Controller直接调这个接口测一下

package com.tzy.userService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GetProductController {

    @Autowired
    GetProductInterface getProductInterface;
    @Autowired
    GetProductService getProductService;

    @RequestMapping(value = "/getGoods")
    public String getGoods(){
        return getProductInterface.getProduct();
    }
}

结果可以得到正确的返回值。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值