服务消费者新增依赖【一般是消费提供者调用服务提供者 版本号我是在父项目定义啦通用版本】
<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
@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
@FeignClient(value = "nacos-payment-provider")
public interface PaymentFeignService {
@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{
@Autowired
private PaymentFeignService paymentFeignService;
@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;
}
}
调用成功【通过访问服务消费者 调用服务提供者】
