项目整体代码请查看Eueka教程
https://blog.csdn.net/qq_38152423/article/details/118737006
第一种 随机策略
父工程pom
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baojiaren</groupId>
<artifactId>eureka</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>eureka-server</module>
<module>eureka-server02</module>
<module>service-provider</module>
<module>service-consumer</module>
<module>service-provider-02</module>
</modules>
<!--继承spring-boot-starter-parent依赖-->
<!--使用继承方式,实现复用,符合继承都可以被使用-->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.3.12.RELEASE</version>
</parent>
<properties>
<spring-cloud.version>Hoxton.SR12</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<!--spring cloud 依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
service-consumer
第一种配置方式, 全局配置,启动类注册Bean
package com.baojiaren;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* @author ✎ℳ๓₯㎕.倾心❀、
* @create 2021-07-15-9:34
*/
@SpringBootApplication
public class ServiceConsumerApplication {
@Bean
public RandomRule randomRule(){
return new RandomRule();
}
@Bean
//@LoadBalanced //负载均衡注解
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ServiceConsumerApplication.class);
}
}
第二种配置方式 单体服务配置
yml配置
server:
port: 9090
spring:
mvc:
hiddenmethod:
filter:
enabled: true
application:
name: service-consumer
freemarker:
prefer-file-system-access: false #是否优先从文件系统加载template
eureka:
instance:
hostname: service-provider #主机名 不配置的时候将根据操作系统的主机名来获取
prefer-ip-address: true #是否使用ip地址注册
instance-id: ${spring.cloud.client.ip-address}:${server.port} #ip port
client:
registerWithEureka: false #是否将自己注册到注册中心,默认为true
serviceUrl: # 注册中心对外暴露的注册地址
defaultZone: http://root:123456@localhost:8761/eureka/,http://root:123456@localhost:8762/eureka/,
registry-fetch-interval-seconds: 10 #表示 Eureka Client 间隔多久去服务器拉取注册信息 默认为30秒
#为所有服务配置统一规则
service-product: #为调用服务的名称
ribbon:
#配置随机策略
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
测试代码
package com.baojiaren.service.impl;
import com.baojiaren.pojo.Order;
import com.baojiaren.pojo.Product;
import com.baojiaren.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* @author ✎ℳ๓₯㎕.倾心❀、
* @create 2021-07-15-10:16
*/
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient; //元数据对象
@Autowired
private LoadBalancerClient loadBalancerClient; // Ribbon 负载均衡器
@Override
public Order selectOrderById(Integer id) {
return new Order(id,"order-001","中国",3199D,selectProductListByLoadBalancerClient());
}
/**
* 第一种元数据方法
* @return
*/
private List<Product> selectProductListByDiscovery(){
StringBuffer sb=null;
//获取服务列表
List<String> serviceIds=discoveryClient.getServices();
if (CollectionUtils.isEmpty(serviceIds)){
return null;
}
// 根据服务名称获取服务
List<ServiceInstance> serviceInstances = discoveryClient.getInstances("service-product");
if (CollectionUtils.isEmpty(serviceInstances)){
return null;
}
ServiceInstance instance = serviceInstances.get(0);
sb=new StringBuffer();
sb.append("http://"+instance.getHost()+":"+instance.getPort()+"/product/list");
ResponseEntity<List<Product>> response = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, new ParameterizedTypeReference<List<Product>>() {
});
return response.getBody();
}
/**
* Ribbon 负载均衡器方式
* @return
*/
private List<Product> selectProductListByLoadBalancerClient(){
StringBuffer sb=null;
//获取服务名称 获取服务
ServiceInstance instance = loadBalancerClient.choose("service-product");
System.out.println(instance);
if (instance==null){
return null;
}
sb=new StringBuffer();
sb.append("http://"+instance.getHost()+":"+instance.getPort()+"/product/list");
System.out.println(sb.toString());
ResponseEntity<List<Product>> response = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, new ParameterizedTypeReference<List<Product>>() {
});
return response.getBody();
}
/**
* 注解方式
* @return
*/
private List<Product> selectProductListByLoadBalancerAnnotation(){
ResponseEntity<List<Product>> response = restTemplate.exchange(
"http://service-product/product/list", HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Product>>() {
});
return response.getBody();
}
}
Controller
package com.baojiaren.controller;
import com.baojiaren.pojo.Order;
import com.baojiaren.service.OrderService;
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;
/**
* @author ✎ℳ๓₯㎕.倾心❀、
* @create 2021-07-15-11:07
*/
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService service;
/**
* 根据主键查询订单
* @param id
* @return
*/
@GetMapping("/{id}")
public Order selectOderById(@PathVariable("id") Integer id){
return service.selectOrderById(id);
}
}
Ribbon 点对点直连
server:
port: 9090
spring:
mvc:
hiddenmethod:
filter:
enabled: true
application:
name: service-consumer
freemarker:
prefer-file-system-access: false #是否优先从文件系统加载template
#eureka:
# instance:
# hostname: service-provider #主机名 不配置的时候将根据操作系统的主机名来获取
# prefer-ip-address: true #是否使用ip地址注册
# instance-id: ${spring.cloud.client.ip-address}:${server.port} #ip port
# client:
# registerWithEureka: false #是否将自己注册到注册中心,默认为true
# serviceUrl: # 注册中心对外暴露的注册地址
# defaultZone: http://root:123456@localhost:8761/eureka/,http://root:123456@localhost:8762/eureka/,
# registry-fetch-interval-seconds: 10 #表示 Eureka Client 间隔多久去服务器拉取注册信息 默认为30秒
#为所有服务配置统一规则
service-product: #为调用服务的名称
ribbon:
#配置随机策略
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
#指定具体的provider 服务列表, 多个用逗号隔开
listOfServers: http://localhost:7070,http://localhost:7071
#关闭 Eureka 实现Ribbon 点对点直连
ribbon:
eureka:
enabled: false # false:关闭, true:开启
pom
<?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>eureka</artifactId>
<groupId>com.baojiaren</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>service-consumer</artifactId>
<name>service-consumer</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
访问:http://localhost:9090/order/1 测试