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