目录
Eureka服务端
1.启动类
package com.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class AppEureka {
public static void main(String[] args) {
SpringApplication.run(AppEureka.class, args);
}
}
2.yml
server:
port: 8761
eureka:
instance:
hostname: 192.168.2.190
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
server:
# 测试时关闭自我保护机制,保证不可用服务及时踢出
enable-self-preservation: false
eviction-interval-timer-in-ms: 3000
3.pom
<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.test</groupId>
<artifactId>eureka</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>
</dependencies>
<!--引入spring cloud依赖-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!--添加spring-boot 依赖-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
Eureka客户端
1.启动类
package com.cq;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication
public class AppOrder {
public static void main(String[] args) {
SpringApplication.run(AppOrder.class, args);
}
}
2. yml
server:
port: 8002
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
register-with-eureka: true
fetch-registry: true
instance:
#Eureka服务端在收到最后一次心跳之后等待的时间上限,单位为秒,超过则删除(客户端告诉服务端按照此规则等待自己)
lease-expiration-duration-in-seconds: 3
##Eureka客户端向服务端发送心跳的时间间隔,单位为秒(客户端告诉服务端自己会按照该规则)
lease-renewal-interval-in-seconds: 1
spring:
application:
name: service-client
3. pom
<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.cq</groupId>
<artifactId>client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<!--eureka-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>
</dependencies>
<!--引入spring cloud依赖-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4. 服务发现工具类
package com.cq.controller;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 取模获取服务注册的URL
*
* @author qizhentao
* @version V1.0
*/
@RestController
public class PollURL {
@Autowired
private DiscoveryClient discoveryClient;
//初始化请求数
public static AtomicInteger requestCnt = new AtomicInteger(1);
/**
* 从服务列表中选择一个地址
* @return ip:端口
*/
@RequestMapping("/getUrl")
public String getUrl(){
long currentTimeMillis = System.currentTimeMillis();// 耗时统计
//在注册中心获取对应的服务列表
List<ServiceInstance> list = discoveryClient.getInstances("service-client");
if(list == null) {
return null;
}
//获取服务列表的数量
int serviceSize = list.size();
//请求数 % 服务列表数量 得到下标
int index = requestCnt.get() % serviceSize;
//将请求数增加1
requestCnt.incrementAndGet();
//根据计算的下标选取一个服务地址
System.out.println("选址用时:"+(System.currentTimeMillis() - currentTimeMillis));
return list.get(index).getUri().toString();
}
}
4.1 修改服务发现工具类-用于正式环境
package com.chuangqi.core.rpc;
import com.chuangqi.core.Conf;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* RPC服务发现,从Eureka获取服务地址
*
* @author qizhentao
* @version V1.0
*/
@Log4j2
public class ServerDiscover {
// RPC远程调用案例说明!
/**
// Eureka客户端
@Resource
private DiscoveryClient discoveryClient;
//调用sim-node-server服务的销毁资源方法
@GetMapping("/getUrl")
public String getUrl() {
// 1. 封装参数
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("_method", "delete"); // 表示是Restful形式的delete请求
// 2. 获取服务ip:port
String address = ServerDiscover.getSimNodeServerAddress(discoveryClient);
// 3. RPC远程调用具体接口
String post = HttpUtil.post(address + "/master-node/resource", paramMap);
return post;
}
*/
/** 初始化请求数Eureka */
public static AtomicInteger requestCnt = new AtomicInteger(1);
/**
* 获取‘1服务’集群中的一个地址
*
* @return ip:port
*/
public static String getSimDisplayServerAddress(DiscoveryClient client) {
return new ServerDiscover().getChooseAddress("1服务名称", client);
}
/**
* 获取‘2服务’集群中的一个地址
*
* @return ip:port
*/
public static String getSimNodeServerAddress(DiscoveryClient client) {
return new ServerDiscover().getChooseAddress("2服务名称", client);
}
/**
* 根据服务名称从服务列表中获取一个地址
*
* @param serverName 服务名
* @param client Eureka客户端接口DiscoveryClient
* @return ip:port
*/
public static String getAddress(String serverName, DiscoveryClient client) {
return new ServerDiscover().getChooseAddress(serverName, client);
}
private String getChooseAddress(String serverName, DiscoveryClient client) {
long start = System.currentTimeMillis();// 耗时统计
//在注册中心获取对应的服务列表
List<ServiceInstance> list = client.getInstances(serverName);
if (list == null || list.size() == 0) {
log.info("{}未发现服务", serverName);
return "";
}
//获取服务列表的数量
int serviceSize = list.size();
//请求数 % 服务列表数量 得到下标
int index = requestCnt.get() % serviceSize;
//将请求数增加1
requestCnt.incrementAndGet();
//根据计算的下标选取一个服务地址
String address = list.get(index).getUri().toString();
long end = System.currentTimeMillis();
log.info("{}服务选址{}耗时:{}", serverName, address, end - start);
return address;
}
}