RestTemplate
/**
* 创建RestTemplate并注入Spring容器
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@LoadBalanced 注解需要使用 Spring Cloud
搭建Eureka服务器
maven坐标
<!--eureka注册中心服务端--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>
yaml文件中配置Eureka
server: port: 10086 #服务端口 spring: application: name: eurekaserver #eureka服务的名字 eureka: client: service-url: #eureka的地址信息 defaultZone: http://localhost:10086/eureka
- 服务端模块的启动类上开启eureka @EnableEurekaServer
package cn.itcast.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
客户端服务注册
客户端依赖
<!--eureka客户端--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
- yaml配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/cloud_order?useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
application:
name: orderservice #order服务(eureka)
eureka:
client:
service-url: #eureka的地址信息
defaultZone: http://localhost:10086/eureka
userservice:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #均衡负载策略
ribbon:
eager-load:
enabled: true
clients: #指定开启饥饿加载的服务名称
- userservice
首先: 跟server一样要设置名字
其次: 顺手选择了负载均衡策略和开启饥饿加载
负载均衡策略需要在客户端RestTepmlate上@LoadBalanced才会生效
userservice:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #均衡负载策略
ribbon:
eager-load:
enabled: true
clients: #指定开启饥饿加载的服务名称
- userservice
使用template
String url = "http://userservice/user/" + userId;//构建url 让temple访问
User user = restTemplate.getForObject(url, User.class);//使用restTemplate发送请求