springcloud微服务(六)—— 基于feign远程调用

springcloud微服务(六)—— 基于feign远程调用

前面我们远程调是通过直接输入url方式来实现的,这样写不利于维护,也不够优雅。本节使用feign能够优雅的实现远程调用。

1.引入依赖

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

注意nacos中的ribbon会使loadbalanc包失效,我们将nacos依赖中的ribbon剔除。(feign具有负载均衡功能)

        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
            
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.cloudgroupId>
                    <artifactId>spring-cloud-starter-netflix-ribbonartifactId>
                exclusion>
            exclusions>
            <version>2.2.5.RELEASEversion>
        dependency>

2.在需要进行远程调用服务的启动类中开启feign,添加@EnableFeignClients注解。

@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication {

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

}

3.编写feign客户端。

package com.bzw.clients;


import com.bzw.domain.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient("userservice") //服务名称
public interface UserClient {

    @GetMapping("/user/{userId}") //请求方式路径
    User findById(@PathVariable("userId") Long id); //请求参数,返回类型
}

4.调用

package com.bzw.service.impl;

import com.bzw.clients.UserClient;
import com.bzw.domain.TbOrder;
import com.bzw.domain.User;
import com.bzw.mapper.TbOrderMapper;
import com.bzw.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private UserClient userClient;

    public TbOrder findOrderById(Long id) {
//       查询订单
        TbOrder tbOrder = tbOrderMapper.selectByPrimaryKey(id);
//        用feign远程调用
        User user = userClient.findById(tbOrder.getUserId());
//        封装User到Order
        tbOrder.setUser(user);
//        返回
        return tbOrder;
    }

}

5.测试

访问 localhost:8080/order/101

springcloud微服务(六)—— 基于feign远程调用_第1张图片

你可能感兴趣的:(微服务,spring,cloud,微服务,java)