需要注册的一方通常都是被调取的一方,我们称之为生产者,以及需要调取的一方,我们称之为消费者,那么这两者都需要通过注册中心去完成调用和被调用的过程.所以谁用到了Nacos,谁就需要导入Nacos的依赖
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
#访问nacos spring.cloud.nacos.discovery.server-addr=localhost:8848 #设置实例名称 spring.application.name=lrs-order #设置不注册 该配置只需在调取的一方中加入,即消费者中加入 spring.cloud.nacos.discovery.register-enabled=false
在nacos所在的目录下的bin中打开cmd窗口并输入以下内容让其以单机模式启动:
startup.cmd -m standalone

通过DiscoveryClient类,我们可以调取服务地址来替换手写url路径

- @Bean
- @LoadBalanced
- public RestTemplate restTemplate(){
- return new RestTemplate();
- }

Ribbon中的策略模式有以下几种:

我们使用了Ribbon以后,地址也不需要通过DiscoveryClient类来获取url再拼接了,我们只需要将其中的路径换位被请求模块在注册中心中的实例名称.

并且在集群化模式下,这种访问模式.会自动帮我们按照我们设定好的负载均衡策略去调用对应的模块所在服务器
org.springframework.cloud spring-cloud-starter-openfeign
- @SpringBootApplication
- @EnableFeignClients
- public class OrderApp {
- public static void main(String[] args) {
- SpringApplication.run(OrderApp.class,args);
- }
-
- @Bean
- @LoadBalanced
- public RestTemplate restTemplate(){
- return new RestTemplate();
- }
- }
想要调用谁,就给谁做伪客户端,就好像将跨服务调用变得像本地调用一样丝滑

该类上一定要加入@FeignClient注解,其中的value值为对应服务(也就是被调用的服务)的实例名称
ProductFeign
- package com.lrs.order.feign;
-
- import com.lrs.common.entity.Product;
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
-
- /**
- * @作者:刘壬杉
- * @创建时间 2022/8/19 17:18
- **/
- @FeignClient(value = "lrs-product")
- public interface ProductFeign {
- @GetMapping("product/getById/{id}")
- public Product getById(@PathVariable Integer id);
- }
并且路径要和原服务上的路径相同,方法的返回类型也要相同,传入的参数也要相同.缺一不可

org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.boot spring-boot-starter-web
- server.port=7000
-
- spring.application.name=eureka-server
-
- #实例的主机名
- eureka.instance.hostname=localhost
-
- #是否把eureka服务端注册到注册中心
- eureka.client.register-with-eureka=false
-
- #该服务是否从注册中心拉取服务
- eureka.client.fetch-registry=false
-
- #提供类微服务的地址
- eureka.client.service-url.defaultZone=http://localhost:7000/eureka
- package com.lrs.eureka;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
-
- /**
- * @作者:刘壬杉
- * @创建时间 2022/8/19 17:27
- **/
- @SpringBootApplication
- @EnableEurekaServer
- public class EurekaApp {
- public static void main(String[] args) {
- SpringApplication.run(EurekaApp.class,args);
- }
- }

(1)导入依赖:
注意:别导错了,这个是client客户端,server模块中是server服务端
org.springframework.cloud spring-cloud-starter-netflix-eureka-client
(2)有关配置类
eureka.client.register-with-eureka=false
(3)OpenFeign中自带有Ribbon的jar,所以使用eureka一样可以配合OpenFeign和Ribbon,只需要导入OpenFeign的jar包即可.