美文网首页
Feign客户端远程调用

Feign客户端远程调用

作者: piziyang12138 | 来源:发表于2020-02-28 12:12 被阅读0次
    • 添加依赖
    <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
    
    • 启动类
    #开启feign客户端
    @EnableFeignClients
    @EnableDiscoveryClient
    @SpringBootApplication
    public class ServiceConsumerApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ServiceConsumerApplication.class, args);
        }
    }
    
    • 创建一个 Feign客户端的接口:MemberServiceFeign
    @FeignClient( value = "app-itmayiedu-member" )#value为注册中心中的serviceId
    public interface MemberServiceFeign{
    
        @RequestMapping("/test")
        String consumer( @RequestParam("param") String param );
    }
    
    • 创建service
    @RestController
    public class OrderService implements IOrderService {
    
        @Autowired
        private MemberServiceFeign memberServiceFeign;
    
        @RequestMapping(value = "/orderToMember",method = RequestMethod.GET)
        public String orderToMember(String name) {
            User member = memberServiceFeign.getMember(name);
            return member == null ? null : member.toString();
        }
    }
    

    到此feign可以正常调用,但是有少许冗余。

    • 项目结构改造
      提供者:
      抽象出一个公共的 API服务
    public interface IMemberService {
    
        @RequestMapping("/getMember")
        public User getMember(@RequestParam("name") String name);
    }
    

    方法实现

    @RestController
    public class MemberService implements IMemberService {
    
        @RequestMapping("/getMember")
        public User getMember(@RequestParam("name") String name) {
            User user = new User();
            user.setName(name);
            user.setUserAge(12);
            return user;
        }
    }
    

    消费者:
    Feign客户端改造

    @FeignClient(value = "app-itmayiedu-member")
    public interface MemberServiceFeign extends IMemberService {
    }
    

    调用方法不变

    public class OrderService implements IOrderService {
    
        @Autowired
        private MemberServiceFeign memberServiceFeign;
    
        @RequestMapping(value = "/orderToMember",method = RequestMethod.GET)
        public String orderToMember(String name) {
            User member = memberServiceFeign.getMember(name);
            return member == null ? null : member.toString();
        }
    }
    

    相关文章

      网友评论

          本文标题:Feign客户端远程调用

          本文链接:https://www.haomeiwen.com/subject/xvwkhhtx.html