SpringCloud学习笔记----SpringCloud 配置nacos注册中心之后 使用Openfegin实现远程调用

220 阅读1分钟

服务消费者新增依赖【一般是消费提供者调用服务提供者 版本号我是在父项目定义啦通用版本】

<!--        openfegin-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

服务消费者启动类新增注解

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

@EnableDiscoveryClient
@SpringBootApplication

//openfeign  远程调用客户端
@EnableFeignClients
public class OrderNacosMain83{
    public static void main(String[] args){
        SpringApplication.run(OrderNacosMain83.class,args);
    }
}

service包下创建为服务调用接口

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component

//填写服务提供者在 nacos 注册中心的服务名称
@FeignClient(value = "nacos-payment-provider")
public interface PaymentFeignService {

    /**
     * 服务提供者的 controller层的接口和方法
     * @param id
     * @return
     */
    @GetMapping(value = "/payment/nacos/{id}")
    public String getPayment(@PathVariable("id") Long id);
}

controller层利用微服务接口调用远程服务

import com.wang.service.PaymentFeignService;
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.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@RestController
@Slf4j
public class OrderNacosController{
//    @Resource
//    private RestTemplate restTemplate;

    @Autowired
    private PaymentFeignService paymentFeignService;

//    @Value("${service-url.nacos-user-service}")
//    private String serverURL;

    @GetMapping(value = "/consumer/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Long id){
       return paymentFeignService.getPayment(id);
    }

}

服务提供者controller层 跟微服务接口的方法和注解参数是一样的

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PaymentController {

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

    //微服务接口的注解跟方法参数 跟当前接口一定得保持一致
    @GetMapping(value = "/payment/nacos/{id}")
    public String getPayment(@PathVariable("id") Long id) {
        return "nacos registry, serverPort: "+ serverPort+"\t id"+id;
    }
}

调用成功【通过访问服务消费者 调用服务提供者】

image.png