可以使用Ribbon负载均衡:在执行RestTemplate发送服务地址请求的时候,使用负载均衡拦截器拦截,根据服务名获取服务地址列表,使用Ribbon负载均衡算法从服务地址列表中选择一个服务地址,访问该地址获取服务数据。
主要配置
- Eureka客户端工程
- user_service 服务提供
- 启动多个user-service实例(9090,9092)
- consumer_demo 服务消费
- 修改RestTemplate实例化方法,添加负载均衡注解@LoadBalanced
- 修改ConsumerController
Eureka服务
Eureka是服务注册中心,只做服务注册;自身并不提供服务也不消费服务。可以搭建web工程使用Eureka,可以使用Spring Boot方式搭建。spring-cloud-starter-netflix-eureka-server中已有Ribbon依赖,不需要另外导入坐标。
导入坐标
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud_parent</artifactId>
<groupId>li.chen.com</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>eureka_service</artifactId>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
</project>
配置文件
- application.yml
server:
port: 10086
spring:
application:
name: eureka_server
eureka:
client:
service-url:
# eureka 服务地址,如果是集群的话;需要指定其它集群eureka地址
defaultZone: http://127.0.0.1:10086/eureka
# 不注册自己 集群才需要
register-with-eureka: false
# 不拉取服务
fetch-registry: false
server:
# 服务失效剔除时间间隔,默认60秒(单位毫秒)
eviction-interval-timer-in-ms: 60000
# 关闭自我保护模式(默认是打开的;即爆红提示,开发时可关闭)
enable-self-preservation: false
创建启动类
package li.chen.com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @ClassName: EurekaServerApplication
* @Description 启动引导类
* @EnableEurekaServer 声明当前类为Eureka服务
**/
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class,args);
}
}
测试
启动 EurekaServerApplication
访问路径 http://127.0.0.1:10086/
服务注册(user_service)
导入坐标
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud_parent</artifactId>
<groupId>li.chen.com</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>user_service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 通用Mapper启动器 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
</project>
配置文件
- application.yml
server:
port: ${port:9090}
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db2
username: root
password: root
application:
name: UserService
mybatis:
type-aliases-package: li.chen.com.user.pojo
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
# 更倾向使用ip地址,而不是host名
prefer-ip-address: true
# ip地址
ip-address: 127.0.0.1
# 续约间隔 ,默认30秒
lease-renewal-interval-in-seconds: 5
# 服务失效时间, 默认90秒
lease-expiration-duration-in-seconds: 5
复制UserApplication9090,并添设置端口9092
-Dport=9092
springboot启动类
- UserApplication
package li.chen.com.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("li.chen.com.user.mapper")
@EnableDiscoveryClient //开启Eureka客户端发现功能
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
各层文件
pojo层
- User
package li.chen.com.user.pojo;
import lombok.Data;
import tk.mybatis.mapper.annotation.KeySql;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Table(name = "user") //对应的数据库表
public class User {
@Id
@KeySql(useGeneratedKeys = true) //主键回填
private Integer id;
@Column(name="userName")
private String userName;
@Column(name="passWord")
private String passWord;
private Date birthday;
}
mapper层
- UserMapper
package li.chen.com.user.mapper;
import li.chen.com.user.pojo.User;
import tk.mybatis.mapper.common.Mapper;
public interface UserMapper extends Mapper<User> {
}
service层
- UserService
package li.chen.com.user.service;
import li.chen.com.user.mapper.UserMapper;
import li.chen.com.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User queryById(Long id){
return userMapper.selectByPrimaryKey(id);
}
}
controller层
- UserController
package li.chen.com.user.controller;
import li.chen.com.user.pojo.User;
import li.chen.com.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/UserController")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User queryById(@PathVariable Long id){
return userService.queryById(id);
}
}
测试
启动UserApplication9090;UserApplication9092
访问 http://127.0.0.1:9090/UserController /2
服务发现(consumer-demo)
服务发现:在服务消费工程consumer-demo上添加Eureka客户端依赖;可以使用工具类根据服务名称获取对应的服务地址列表。
导入坐标
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springcloud_parent</artifactId>
<groupId>li.chen.com</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>consumer_demo</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
</project>
配置文件
- application.yml
spring:
application:
name: consumer_demo
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
# 获取服务地址列表间隔时间,默认30秒
registry-fetch-interval-seconds: 10
springboot启动类
- ConsumerApplication
package li.chen.com.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient //开启Eureka客户端发现功能
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
各层文件
pojo层
- User
package li.chen.com.consumer.pojo;
import lombok.Data;
import java.util.Date;
/**
* @ClassName: User
* @Description 接收数据,不进行数据库交互,故不需要加user_service里的那些注解
**/
@Data
public class User {
private Integer id;
private String userName;
private String passWord;
private Date birthday;
}
controller层
- UserController
package li.chen.com.consumer.controller;
import li.chen.com.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* @ClassName: ConsumerController
* @Description 请描述下该类是做什么的
* @Author lichen
* @Date 2021/2/15 18:12
* @Verson 1.0
**/
@RestController
@RequestMapping("/ConsumerController")
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/{id}")
public User queryById(@PathVariable Integer id) {
String url = "http://UserService/UserController/" + id;
/*
注意:UserService 不能写为user_service ;
对于Ribbon的服务名称不要加下划线,否则无法解析具体的地址。
[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Request URI does not contain a valid hostname
*/
return restTemplate.getForObject(url, User.class);
}
}
测试
1 先启动 EurekaServerApplication,UserApplication9090,UserApplication9092
2 找到 RibbonLoadBalancerClient 的 execute方法,打断点
3 再以debug方式启动ConsumerApplication
4 访问 http://localhost:8080/ConsumerController/7
查看断点显示的端口号为9090;F9 放行
再次刷新 http://localhost:8080/ConsumerController/7
查看断点显示的端口号为9090;(Ribbon默认模式轮询)
注意:对于Ribbon的服务名称不要加下划线,否则无法解析具体的地址。解决方案
实例化RestTemplate的时候使用@LoadBalanced,服务地址直接可以使用服务名。
服务发现中配置Ribbon负载均衡策略
默认为轮询,可以不配置yml,故上面的consumer-demo的yml中没有配置Ribbon
application.yml
server:
# 端口设置 有传参使用传参值;没有使用默认10086
port: ${port}
spring:
application:
name: eureka_server
eureka:
client:
service-url:
# eureka 服务地址,如果是集群的话;需要指定其它集群eureka地址
# 端口设置 有传参使用传参值;没有使用默认 http://127.0.0.1:10086/eureka
defaultZone: http://127.0.0.1:10086/eureka/,http://127.0.0.1:10087/eureka/
# 集群才需要
register-with-eureka: false
# 不拉取服务
fetch-registry: false
server:
# 服务失效剔除时间间隔,默认60秒(单位毫秒)
eviction-interval-timer-in-ms: 60000
# 关闭自我保护模式(默认是打开的;即爆红提示,开发时可关闭)
enable-self-preservation: false
# 配置 ribbon负载均衡策略:随机 /不配置,默认为轮询
UserService: # 需要 负载均衡的 服务名称
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule