eureka之服务注册与发现

吃可爱长大的小学妹 提交于 2019-12-10 10:01:32

eurekaServer与eurekaClient关系

  • Eureka Client:一个Java客户端,用于简化与 Eureka Server 的交互(通常就是微服务中的客户端和服务端)
  • Eureka Server:提供服务注册和发现的能力(通常就是微服务中的注册中心)
    服务注册与发现

一、搭建eureka server

1.1引入pom依赖

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

1.2配置application.properties

#eureka server端口
server.port=9000
spring.application.name=eurekaServer
#eureka配置
eureka.instance.hostname=localhost
#是否将自己注册到注册中心
eureka.client.register-with-eureka=false
#是否从eureka获取注册信息
eureka.client.fetch-registry=false
#暴露给Eureka Client的请求地址
eureka.client.service-url.defaultZone=http://localhost:9000/eureka/

#开发的时候配置这两项,正式上线保留
#关闭自我保护
eureka.server.enable-self-preservation=false
#剔除服务时间(毫秒)
eureka.server.eviction-interval-timer-in-ms=4000

1.3编写启动类

@SpringBootApplication
// 激活eurekaServer
@EnableEurekaServer
public class EurekaServerApplication {

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

启动EurekaServerApplication即搭建完成。

1.4测试地址

http://localhost:9000/eureka

2注册微服务到EurekaServer

2.1创建微服务提供者

pom文件

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		
		<!-- 引入EurekaClient -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
	</dependencies>

application.properties配置

server.port=9001
spring.application.name=product-service
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.open-in-view=true

#配置eurekaClient
eureka.client.service-url.defaultZone=http://localhost:9000/eureka/
#使用IP地址注册
eureka.instance.prefer-ip-address=true
#在eurekaServer注册列表中以IP显示
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
#续约到期时间(每5秒发送一次心跳)
eureka.instance.lease-renewal-interval-in-seconds=5  
eureka.instance.lease-expiration-duration-in-seconds=10
  

dao和serverice层省略,action层代码

@RestController
@RequestMapping("/product")
public class ProductController {
	
	@Autowired
	private ProductService productService;
	
	@Value("${spring.cloud.client.ip-address}")
	private String ip;
	
	@Value("${server.port}")
	private String port;
	
	@RequestMapping(value="/{id}",method=RequestMethod.GET)
	public Product findProductById(@PathVariable Long id){
		Product product = productService.findById(id);
		product.setProduct_name(ip+":"+port);
		return product;
	}
	
	@RequestMapping(value="/save",method=RequestMethod.GET)
	public String save(Product product){
		productService.save(product);
		return "保存成功";
	}

启动类

@SpringBootApplication
@EntityScan("com.yan.product.entity")
//激活EurekaClient
//@EnableEurekaClient
@EnableDiscoveryClient
public class ProductApplication {
	
	public static void main(String[] args) {
		SpringApplication.run(ProductApplication.class, args);
	}
}

2.1创建微服务消费者

pom文件

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<!-- 引入EurekaClient -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>

	</dependencies>

application.properties配置

server.port=9002
spring.application.name=order-service
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.open-in-view=true

#配置eurekaClient
eureka.client.service-url.defaultZone=http://localhost:9000/eureka/
#使用IP地址注册
eureka.instance.prefer-ip-address=true

通过spring提供的RestTemplate发送http请求调用服务调用层代码

@RestController
@RequestMapping("/order")
public class OrderController {
	
	@Autowired
	private RestTemplate restTemplete;
	
	@Autowired
	private DiscoveryClient discoveryClient;
	
	@RequestMapping(value="/findById/{id}")
	public String findById(@PathVariable Long id){
		Product product = null;
		product = restTemplete.getForObject("http://product-service/product/"+id, Product.class);
		return product.toString();
	}
	
	@RequestMapping(value="/save")
	public String save(){
		List<ServiceInstance> instances = discoveryClient.getInstances("product_service");
		for (ServiceInstance serviceInstance : instances) {
			System.out.println(serviceInstance.getHost());
			System.out.println(serviceInstance.getPort());
		}
//		restTemplete.getForObject("http://localhost:9001/product/save?status=1", Product.class);
		return "保存成功";
	}
	
//	@RequestMapping(value="/findById/{id}")
//	public String findById(@PathVariable Long id){
//		System.out.println(id);
//		Product product = restTemplete.getForObject("http://localhost:9001/product/"+id, Product.class);
//		return product.toString();
//	}
	
}

启动类

@SpringBootApplication
@EntityScan("com.yan.order.entity")
@EnableDiscoveryClient
public class OrderApplication {
	
	@Bean
	//@LoadBalanced
	public RestTemplate getRestTemplete(){
		return new RestTemplate();
	}
	
	public static void main(String[] args) {
		SpringApplication.run(OrderApplication.class, args);
	}
}

至此,启动eureka server ,微服务提供者、消费者三个服务,在eureka server管理平台即可看到两个注册上去的微服务。

3EurekaServer的高可用

eureka server可以同时存在多个,多个服务之间需要相互注册。
application.properties配置文件

#eureka server端口
server.port=8000
spring.application.name=eurekaServer
#eureka配置
eureka.instance.hostname=localhost
#是否将自己注册到注册中心
eureka.client.register-with-eureka=true
#是否从eureka获取注册信息
eureka.client.fetch-registry=true
#暴露给Eureka Client的请求地址
eureka.client.service-url.defaultZone=http://localhost:8000/eureka/

#开发的时候配置这两项,正式上线保留
#关闭自我保护
eureka.server.enable-self-preservation=false
#剔除服务时间(毫秒)
eureka.server.eviction-interval-timer-in-ms=4000

微服务的提供者和消费者也需要同时注册到所有的eureka server上,多个注册服务之间用英文逗号隔开。

#配置eurekaClient
eureka.client.service-url.defaultZone=http://localhost:8000/eureka/,http://localhost:9000/eureka/

4服务注册与发现源码分析

https://www.cnblogs.com/trust-freedom/p/10310606.html

5 eureka注解原理

通过springboot加载外部配置类类似,主要是通过@ImportSelect注解实现。
1、定义一个需要使用的类User
2、建立一个配置

import org.springframework.context.annotation.Bean;

public class UserConfig {
	
	@Bean
	public User getUser(){
		User user = new User();
		user.setName("***");
		user.setAge(23);
		return user;
	}
	
}

3、实现ImportSelector

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

public class UserImportSeletor implements ImportSelector{

	@Override
	public String[] selectImports(AnnotationMetadata arg0) {
		//获取配置类的名称
		return new String[]{UserConfig.class.getName()};
	}

}

4、创建一个注解

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Import;

@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.TYPE)
@Import(UserImportSeletor.class)
public @interface EnableUserBean {

}

5、测试使用

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@EnableUserBean
public class TestApplication {
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestApplication.class);
		User user = ac.getBean(User.class);
		System.out.println(user);
		ac.close();
	}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!