0
点赞
收藏
分享

微信扫一扫

SpringCloud - Feign


SpringCloud - Feign_RestTemplate

package com.imooc.product.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ServerController {

@GetMapping("/msg")
public String msg() {
return "this is product' msg";
}
}
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
package com.imooc.order;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderApplication {

public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
package com.imooc.order.client;

import com.imooc.order.dataobject.ProductInfo;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;

@FeignClient(name = "product")
public interface ProductClient {

@GetMapping("/msg")
String productMsg();

@PostMapping("/product/listForOrder")
List<ProductInfo> listForOrder(@RequestBody List<String> productIdList);
}
package com.imooc.order.controller;

import com.imooc.order.client.ProductClient;
import com.imooc.order.dataobject.ProductInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;

@RestController
@Slf4j
public class ClientController {

@Autowired
private ProductClient productClient;

@GetMapping("/getProductMsg")
public String getProductMsg() {
String response = productClient.productMsg();
log.info("response={}", response);
return response;
}

@GetMapping("/getProductList")
public String getProductList() {
List<ProductInfo> productInfoList = productClient.listForOrder(Arrays.asList("164103465734242707"));
log.info("response={}", productInfoList);
return "ok";
}
}

Feign用来进行应用之间的通信,在order项目中调用商品服务,应用feign

  1. 用的时候需要在pom.xml添加feign依赖。
  2. 在启动主类(OrderApplication)上加注解@EnableFeignClients。
  3. 在客户端定义好要调用的服务和接口(ProductClient),这里是要调用商品服务的商品详情接口productMsg(),主要是通过@FeignClient匹配服务@GetMapping匹配方法的。
  4. 在客户端添加ClientController类,依赖注入ProductClient,调用ProductClient的getProductMsg()。

SpringCloud - Feign_SpringCloud_02

  • Feign 主要是 feign client + ribbon,feign其实就通过@FeignClient注解的接口的serviceName+ribbon拿到目标服务ip和port,然后根据@FeignClient注解的接口的某个方法上的requestMapping注解,组装成完整的请求url,然后利用restTemplate去请求目标url。


举报

相关推荐

0 条评论