(七)feign-简化服务调用

前面的章节虽然完成了服务的注册以及相互间的调用,但是调用方发起调用时,还是硬编码的形式,如果服务比较多,代码不好管理。如,用户服务调用订单服务:

    @PostMapping("/findOrderList")
    public JSONArray findOrderList() throws Exception {
        String serviceId = "ORDER";
        String url = "http://" + serviceId + "/order/findOrderList";
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(null, headers);

        JSONArray responseEntity
                = restTemplate.postForObject(url, formEntity, JSONArray.class);
        return responseEntity;
    }

feign很好的封装了这些调用细节,可以使得客户端像调用本地方法一样调用远程服务。

service-api模块

新增service-api模块,统一管理接口,用户服务和订单服务都依赖该模块。
(七)feign-简化服务调用_第1张图片

  1. pom文件配置

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>eureka-parentartifactId>
        <groupId>com.ftgroupId>
        <version>0.0.1-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>service-apiartifactId>


    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.retrygroupId>
            <artifactId>spring-retryartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-hystrixartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-zuulartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.51version>
        dependency>
        <dependency>
            <groupId>com.squareup.okhttp3groupId>
            <artifactId>okhttpartifactId>
            <version>4.2.2version>
        dependency>
    dependencies>
project>
  1. OrderControllerApi.java
@RequestMapping("order")
@FeignClient(value = "order") // 当前类视为客户端,并指定服务别名
public interface OrderControllerApi {

    /**
     * 查询所有订单列表
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/findOrderList")
    public JSONArray findOrderList() throws Exception;

    @GetMapping("/hello")
    public String hello();

}
  1. UserControllerApi.java
@RequestMapping("user")
public interface UserControllerApi {

    /**
     * 查询所有订单列表
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/findOrderList")
    public JSONArray findOrderList() throws Exception;

    @GetMapping("/hello")
    public String hello();

}

订单服务

  1. 订单服务pom.xml依赖service-api

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>eureka-parentartifactId>
        <groupId>com.ftgroupId>
        <version>0.0.1-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>orderartifactId>

    <dependencies>
        
        <dependency>
            <groupId>com.ftgroupId>
            <artifactId>service-apiartifactId>
            <version>0.0.1-SNAPSHOTversion>
        dependency>
    dependencies>

project>
  1. 订单服务OrderController实现service-api里的OrderControllerApi
@RestController
public class OrderController implements OrderControllerApi {

    @Value("${server.port}")
    private String port;

    @Override
    public JSONArray findOrderList() throws Exception {
        JSONArray orderList = new JSONArray();
        JSONObject o1 = new JSONObject();
        o1.put("ordNo", "001");
        o1.put("ordName", "鼠标");
        JSONObject o2 = new JSONObject();
        o2.put("ordNo", "002");
        o2.put("ordName", "键盘");
        JSONObject o3 = new JSONObject();
        o3.put("port", port);
        System.out.println("port=" + port);
        orderList.add(o1);
        orderList.add(o2);
        orderList.add(o3);
        return orderList;
    }


    @Autowired
    public String hello() {
        return "hello order!!!";
    }

}

用户服务

  1. 用户服务pom.xml依赖service-api

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>eureka-parentartifactId>
        <groupId>com.ftgroupId>
        <version>0.0.1-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>userartifactId>

    <dependencies>
        
        <dependency>
            <groupId>com.ftgroupId>
            <artifactId>service-apiartifactId>
            <version>0.0.1-SNAPSHOTversion>
        dependency>
    dependencies>

project>
  1. 用户服务UserController实现service-api里的UserControllerApi
@RestController
public class UserController implements UserControllerApi {
    
    @Autowired
    private OrderControllerApi orderControllerApi;

    @Override
    public JSONArray findOrderList() throws Exception {
    	// 发起调用订单服务
        JSONArray result = orderControllerApi.findOrderList();
        return result;
    }

    @Override
    public String hello() {
        return "hello user!!!";
    }
}

测试

postman测试结果跟之前的完全一致。
(七)feign-简化服务调用_第2张图片

feign日志调试

用户服务使用feign调用订单服务,如果需要查看feign的调用日志,那么就需要开启相关配置。

  1. 用户服务application.yml增加如下配置:
logging:
  level:
    # 针对订单api设置日志级别
    com.ft.api.controller.OrderControllerApi: debug

# 配置feign
feign:
  client:
    config:
      # 配置服务提供方的名称
      order:
        loggerLevel: FULL
  1. postman发起调用后,查看用户服务控制台日志。
2022-02-08 21:28:40.393 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] <--- HTTP/1.1 200 (290ms)
2022-02-08 21:28:40.393 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] connection: keep-alive
2022-02-08 21:28:40.394 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] content-type: application/json
2022-02-08 21:28:40.394 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] date: Tue, 08 Feb 2022 13:28:40 GMT
2022-02-08 21:28:40.394 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] keep-alive: timeout=60
2022-02-08 21:28:40.394 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] transfer-encoding: chunked
2022-02-08 21:28:40.394 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] 
2022-02-08 21:28:40.398 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] [{"ordNo":"001","ordName":"鼠标"},{"ordNo":"002","ordName":"键盘"},{"port":"8012"}]
2022-02-08 21:28:40.398 DEBUG 22352 --- [nio-8001-exec-1] c.ft.api.controller.OrderControllerApi   : [OrderControllerApi#findOrderList] <--- END HTTP (87-byte body)
2022-02-08 21:28:41.239  INFO 22352 --- [erListUpdater-0] c.netflix.config.ChainedDynamicProperty  : Flipping property: order.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2022-02-08 21:32:18.383  INFO 22352 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2022-02-08 21:37:18.385  INFO 22352 --- [trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration

你可能感兴趣的:(springcloud,java,微服务,http)