1️⃣搭建服务
引入依赖
xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
启动类加注解
java
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,args);
}
}
改配置
yml
server:
port: 10086
spring:
application:
name: eurekaserver # eureka服务名称
eureka:
client:
service-url: # eureka服务地址
defaultZone: http://127.0.0.1:10086/eureka
2️⃣服务注册
引入依赖
xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
修改配置
yml
spring:
application:
name: userservice
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
3️⃣服务发现和负载均衡
- 服务发现
将请求url中的ip端口换成服务名 如
userservice
- 负载均衡
在RestTemplate添加
@LoadBalanced
注解
java
@MapperScan("cn.zyw.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
4️⃣负载均衡策略
- 代码方式: 定义一个新的IRule:
java
@Bean
public IRule randomRule(){
return new RandomRule();
}
- 配置文件方式:在application.yml文件中
yml
userservice: # 要配置的微服务名称
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 负载均衡规则
5️⃣饥饿加载
yml
ribbon:
eager-load:
enabled: true # 开启饥饿加载
clients: # 指定饥饿加载的服务名称
- userservice