一、Eureka服务的搭建
1、搭建EurekaServer
- 在父pom.xml文件中需要引入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency>
- 在pom.xml文件中引入eureka-server依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>
- 添加@EnableEurekaServer注解到启动类上
- 在配置文件中配置eureka地址信息 (如下所示,具体端口和名称可自行更改)
spring: application: name: eurekaserver #服务名称 eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka/ #地址信息
启动项目之后可以访问网站进行查看。
2、服务注册
- 在pom.xml文件中引入eureka-client依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
- 在配置文件中配置eureka地址信息(地址信息为EurekaServer的地址)
spring: application: name: orderserver #名称 eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka/ #地址信息
3、Ribbon负载均衡
- 代码方式
@Bean
public IRule randomRule(){
return new RandomRule();
}
- 配置方式
#服务名,只针对当前服务的负载均衡 userserver: ribbon: NFLoadBalancerRuleClassName: com.netfilx.loadbalancer.RandomRule #负载均衡规则
4、饥饿加载
ribbon: eager-load: enabled: true #开启饥饿加载 clients: userserver #指定饥饿加载的服务名称。
二、Nacos服务的搭建
1、首先启动nacos:打开cmd窗口,cd 进入到nacos的bin目录下,执行命令:
startup.cmd -m standalone
就启动好了nacos
2、服务注册
- 在父pom.xml文件中需要引入依赖
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.2.5.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency>
- 引入nacos的依赖
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
- 配置nacos地址
spring: application: name: orderserver #服务名称 cloud: nacos: server-addr: localhost:8848 #nacos服务地址 discovery: cluster-name: HZ #集群名称
3、负载均衡
#服务名称 userserver: ribbon: NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule #负载均衡规则