SpringCloud-feign客户端http请求

2020-08-13  本文已影响0人  liangxifeng833
image.png

########################################################

重构feign客户端

以上目录结构说明:
api-service中包含api-member-serviceapi-order-service这两个service只是接口和实体没有实现;
api-member-service-impl是具体的会员服务实现,该项目依赖api-member-service接口.
api-order-service-impl是具体的订单服务实现,该项目依赖 api-order-servcieapi-member-service两个接口项目,在该项目中使用feign客户端调用远程会员服务接口如下:

import api.member.service.IMemberServcie;
import org.springframework.cloud.openfeign.FeignClient;
/**
 * 使用feign客户端调用远程会员服务接口
 * 该接口继承会员服务api-member-service中的IMemberService接口
 * 就不需要重复写接口了
 */
@FeignClient("app-member")
public interface MemberServiceFeign extends IMemberServcie {
}

OrderServiceImpl实现接口并具体实现远程调用内容如下:

package order.service.impl;

import api.member.entity.User;
import order.service.IOrderService;
import order.service.feign.MemberServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 订单服务controller 实现order-service项目中的接口
 */
@RestController
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private MemberServiceFeign memberServiceFeign;


    @RequestMapping("/orderToMember")
    @Override
    public String orderToMember(String name) {
        User user = memberServiceFeign.getMember(name);
        return user==null ? "找不到用户信息" : user.toString();
    }
}

成功访问结果如下:(注意启动项目顺序:eureka-> api-member-service-impl-> api-order-service-impl)公共接口api-server不需要配置启动文件因为只有接口所以无需启动.

image.png
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
package order.service;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
//@EnableEurekaClient 将当前服务注册到Eureka
@EnableEurekaClient
//使用feign客户端调用远程http服务
@EnableFeignClients
public class OrderApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(OrderApplication.class);
    }

}

具体项目代码地址:https://github.com/liangxifeng833/springcloud/tree/master/parent

上一篇 下一篇

猜你喜欢

热点阅读