Spring Cloud服务发现之Eureka

Java版本:1.8

Spring版本:5.1.8.RELEASE

Spring Boot版本:2.1.6.RELEASE

Spring Cloud版本:Greenwich.SR1

Eureka Server 

<?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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sean</groupId>
	<artifactId>eureka-server</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>eureka-server</name>
	<description>eureka-server</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<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>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
package com.sean;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

	public static void main(String[] args) {
		SpringApplication.run(EurekaServerApplication.class, args);
	}

}
server.port=8000
eureka.instance.hostname=localhost

# 是否注册至eureka,默认值为true,如果为true,需要配置eureka.client.service-url.defaultZone
# 否则会访问默认eureka地址:http://localhost:8761/eureka/
# 本服务当做单独的eureka server,不对外提供服务,因此不需要注册到eureka中
eureka.client.register-with-eureka=false
# 是否从eureka拉取服务信息,默认值为true,如果为true,需要配置eureka.client.service-url.defaultZone
# 否则会访问默认eureka地址:http://localhost:8761/eureka/
# 由于仅配置了一台eureka,不需要从其它eureka server拉取信息,所以这里设置为false
eureka.client.fetch-registry=false
# 服务注册中心地址
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka

服务启动后,通过指定的域名和端口,可以访问Eureka的Web Console

 

Test Service

将名称查询服务注册到Eureka中

<?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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sean</groupId>
	<artifactId>test-service</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>test-service</name>
	<description>test-service</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
	</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.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<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>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
package com.sean;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by seanzou on 2019/7/3.
 */
@RestController
@RequestMapping(value = "/")
public class NameController {

    @RequestMapping(value = "/name" , method = RequestMethod.GET)
    public String test(){
        return "sean";
    }
}
package com.sean;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(TestServiceApplication.class, args);
	}

}
server.port=8080
spring.application.name=test-service

eureka.client.service-url.defaultZone=http://localhost:8000/eureka

#服务优先使用ip注册到eureka
eureka.instance.prefer-ip-address=true
# 服务续租任务(发送心跳)执行时间间隔,默认30s
eureka.instance.lease-renewal-interval-in-seconds=10
# 服务过期时间,默认90s
eureka.instance.lease-expiration-duration-in-seconds=20 

服务启动后,可以从日志中看到

Registering application TEST-SERVICE with eureka with status UP

说明服务已经正确注册到了Eureka上

 

Test Client

从Eureka中获取名称服务的地址,之后向该地址发送请求获取查询名称

<?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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sean</groupId>
	<artifactId>test-client</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>test-client</name>
	<description>test-client</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
	</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.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>

		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.2</version>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<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>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

 

package com.sean;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * Created by seanzou on 2019/9/10.
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory){
        return new RestTemplate(clientHttpRequestFactory);
    }

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//ms
        factory.setConnectTimeout(5000);//ms
        return factory;
    }
}
package com.sean;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Created by seanzou on 2019/7/10.
 */
@Component
public class TestService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    public void test(){
        List<ServiceInstance> instances = discoveryClient.getInstances("test-service");
        if(CollectionUtils.isNotEmpty(instances)){
            ServiceInstance instance = instances.get(0);
            String host = instance.getHost();
            Integer port = instance.getPort();

            ResponseEntity responseEntity = restTemplate.getForEntity("http://" + host + ":" + port + "/name", String.class);
            if(responseEntity != null && responseEntity.getStatusCode() != null &&
                    responseEntity.getStatusCode().is2xxSuccessful()){
                String resp = (String)responseEntity.getBody();
                System.out.println(resp);
            }
        }
    }
}
package com.sean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by seanzou on 2019/7/3.
 */
@RestController
@RequestMapping(value = "/")
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping(value = "/test" , method = RequestMethod.GET)
    public void test(){
        testService.test();
    }
}

高版本的Spring Could不需要在启动类配置@EnableDiscoveryClient即可自动将服务注册至Eureka Server上

package com.sean;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestClientApplication {

	public static void main(String[] args) {
		SpringApplication.run(TestClientApplication.class, args);
	}
}
server.port=8090
spring.application.name=test-client

eureka.client.service-url.defaultZone=http://localhost:8000/eureka

# 是否注册至eureka,默认值为true,如果为true,需要配置eureka.client.service-url.defaultZone
# 否则会访问默认eureka地址:http://localhost:8761/eureka/
# 本服务仅供测试,不对外提供服务,因此不需要注册到eureka中
eureka.client.register-with-eureka=false

# 服务续租任务执行时间间隔
eureka.instance.lease-renewal-interval-in-seconds=10
# 服务过期时间
eureka.instance.lease-expiration-duration-in-seconds=20

服务启动后,访问http://localhost:8090/test,日志中成功打印出了从服务端查询的名称sean

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值