二、Spring Cloud 的 Eureka 组件
2017-09-07 21:15
351 查看
Spring 微服务架构
Spring cloud 微服务解决方案(组件集), Spring cloud 他不是一蹴而就的,在不同阶段,引用对应组件:
1) 服务变多了,引入注册中心? Spring Cloud - Eureka
2) 服务间调用的负载均衡? Spring Cloud - Ribbon 客户端负载均衡
3) 配置如何管理?如何动态更新? Spring Cloud - Config
4) 服务限流? Spring Cloud - Hystrix 熔断中心
5) AService -> BService -> CService 调用链路追踪? Spring Cloud - Sleuth
6) 网关代理(鉴权)? Spring Cloud - Zuul
7) 消息总线? Spring Cloud - BUS
Zookeeper 与 Eureka 差别
1) Zookeeper 不是专业处理Eureka的工具
2) 和程序的需要定制开发
3) 选举Leader,不能服务
2) yml 文件配置
3) 主程序代码
2) yml 文件配置
3) 主程序
4) User Entity 类
5) Controller 控制台
6) DAO 层
http://localhost:8100/discovery/1
1) Maven 配置
2) yml 文件配置
3) 主程序
4) User Entntiy 类
5) Controller 控制层
Spring cloud 微服务解决方案(组件集), Spring cloud 他不是一蹴而就的,在不同阶段,引用对应组件:
1) 服务变多了,引入注册中心? Spring Cloud - Eureka
2) 服务间调用的负载均衡? Spring Cloud - Ribbon 客户端负载均衡
3) 配置如何管理?如何动态更新? Spring Cloud - Config
4) 服务限流? Spring Cloud - Hystrix 熔断中心
5) AService -> BService -> CService 调用链路追踪? Spring Cloud - Sleuth
6) 网关代理(鉴权)? Spring Cloud - Zuul
7) 消息总线? Spring Cloud - BUS
Zookeeper 与 Eureka 差别
1) Zookeeper 不是专业处理Eureka的工具
2) 和程序的需要定制开发
3) 选举Leader,不能服务
一、Eureka Server
查看 Eureka Server 的Web管理界面 http://localhost:8761 查看 Eureka Server 的服务实例 http://localhost:8761/eureka/apps 1) Maven配置<?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.itmuch.cloud</groupId> <artifactId>microservice-eureka-server</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>eureka-server</name> <description>Simple for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.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> <spring-cloud.version>Dalston.SR3</spring-cloud.version> </properties> <dependencies> <!-- Eureka 服务 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </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>
2) yml 文件配置
server: port: 8761 eureka: instance: hostname: localhost client: register-with-eureka: false #表示是否将自己注册到Eureka Server中,默认为true, 由于当前应用就是 Eureka Server, 故而设置为false fetch-registry: false #表示是否从 Eureka Server中获取注册信息, 默认为true, 因为这是一个单点的 Eureka Server, 不需要同步其它的 Eureka Server 节点的数据, 故而设置为 false service-url: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # 设置与Eureka Server交互的地址, 查询服务和注册服务都需要依赖这个地址. 默认http://localhost:8761/eureka; 多个地址可以使用","分隔
3) 主程序代码
package com.itmuch.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer // 开启这是一个 Eureka Server 程序 public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
二、生产者程序
1) Maven 配置<?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.itmuch.cloud</groupId> <artifactId>microservice-cloud-service</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>cloud-service</name> <description>Simple for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.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> <spring-cloud.version>Dalston.SR3</spring-cloud.version> </properties> <dependencies> <!-- Spring Eureka 客户端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <!-- Spring Cloud --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> </dependency> <!-- Spring Boot Actuator 监控端口 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- JPA依赖包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- Web项目依赖包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</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>
2) yml 文件配置
server: port: 8080 session: timeout: 30 tomcat: max-threads: 0 uri-encoding: UTF-8 spring: application: #表示注册到Eureka上的应用名称 name: cloud-service datasource: url: jdbc:mysql://localhost:3306/boot username: root password: xshdb driver-class-name: com.mysql.jdbc.Driver jpa: # Specify the DBMS database: MYSQL # Show or not log for each sql query show-sql: true # Hibernate dll auto (create, create-drop, update) hibernate: ddl-auto: update eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true # 表示将自己的IP注册到Eureka Serverk, 如果不配置该属性或将它改为false,则表示注册微服务所在操作系统的hostname到Eureka Server
3) 主程序
package com.itmuch.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class CloudServiceApplication { public static void main(String[] args) { SpringApplication.run(CloudServiceApplication.class, args); } }
4) User Entity 类
package com.itmuch.cloud; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @Entity public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private String username; @Column private String name; @Column private Integer age; @Column private BigDecimal balance; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }
5) Controller 控制台
package com.itmuch.cloud; 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.RestController; @RestController public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/get/{id}") // 在Spring 4.3规则中,@GetMapping等价于@RequestMapping(method = RequestMethod.GET), 用于简化, 同理还有@PostMapping, @PutMapping, @DeleteMapping, @PatchMapping等 public User findById(@PathVariable Long id) { User findOne = this.userRepository.findOne(id); System.out.println(findOne.toString()); return findOne; } }
6) DAO 层
package com.itmuch.cloud; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { }
三、 消费者
测试地址: http://localhost:8100/eureka/1 好像有问题, 根据服务名找不到实例http://localhost:8100/discovery/1
1) Maven 配置
<?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.itmuch.cloud</groupId> <artifactId>microservice-cloud-consumer</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>cloud-consumer</name> <description>Simple for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.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> <spring-cloud.version>Dalston.SR3</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </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>
2) yml 文件配置
server: port: 8100 spring: application: name: cloud-consumer eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true # 表示将自己的IP注册到Eureka Serverk, 如果不配置该属性或将它改为false,则表示注册微服务所在操作系统的hostname到Eureka Server user: userServiceUrl: http://localhost:8080/ userEurekaService: http://cloud-service userEurekaName: cloud-service
3) 主程序
package com.itmuch.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableEurekaClient // 或@EnableDiscoveryClient public class CloudConsumerApplication { @Bean // 等价于 RestTemplate restTemplate = new RestTemplate(); public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(CloudConsumerApplication.class, args); } }
4) User Entntiy 类
package com.itmuch.cloud; import java.io.Serializable; import java.math.BigDecimal; public class User implements Serializable { private static final long serialVersionUID = 1L; private Long id; private String username; private String name; private Integer age; private BigDecimal balance; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } }
5) Controller 控制层
package com.itmuch.cloud; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.ServiceInstance; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class UserController { @Value("${user.userServiceUrl}") // 在yml文件中已经配置, 解决它的硬编码问题 private String userServiceUrl; @Value("${user.userEurekaService}") private String userEurekaService; @Value("${user.userEurekaName}") private String userEurekaName; @Autowired private RestTemplate restTemplate; @Autowired private DiscoveryClient discoveryClient; /** * 基于Spring Boot方式来调用服务 * * 说明:在Spring 4.3规则中,@GetMapping等价于@RequestMapping(method = RequestMethod.GET), 用于简化, 同理还有@PostMapping, @PutMapping, @DeleteMapping, @PatchMapping等 * * @param id * @return */ @GetMapping("/user/{id}") public User findById(@PathVariable Long id) { return this.restTemplate.getForObject(this.userServiceUrl + id, User.class); } /** * #1 第一种 基于Eureka服务方式来调用 * * @param id * @return */ @GetMapping("/eureka/{id}") public User findByIdEureka(@PathVariable Long id) { User user = this.restTemplate.getForObject("http://cloud-service/get/" + 1, User.class); return user; } /** * #2 第二种 基于Eureka服务方式来调用 * * @param id * @return * @throws MalformedURLException */ @GetMapping("/discovery/{id}") public Object findByIdDiscovery(@PathVariable Long id) throws Exception { // 非配置 IP 端口 // 通过服务名获取实例 // Eureka 会缓存, 不是每个请求都会调用 EurekaServer接口 List<ServiceInstance> instances = discoveryClient.getInstances(this.userEurekaName); // 获取到一个服务器列表,如1.2.3 // 随机、轮询, ribbon客户端负责均衡 // 熔断 Hystrix ServiceInstance serviceInstance = instances.get(0); String host = serviceInstance.getHost(); int port = serviceInstance.getPort(); URL url = new URL("http://" + host + ":" + port + "/get/" + id); byte[] result = new byte[3]; InputStream input = url.openStream(); IOUtils.readFully(input, result); System.out.println(new String(result)); return new String(result); } }
相关文章推荐
- Spring Cloud Netflix Eureka组件服务注册及发现源码浅析
- Spring Cloud 组件搭建(一)Eureka服务发现
- spring cloud服务发现组件Eureka详解
- SpringCloud(三):服务发现组件Eureka
- SpringCloud 服务发现组件 Eureka
- SpringCloud 服务发现组件 Eureka的初步学习
- Spring Cloud Netflix的3大组件应用 Eureka&Ribbon&Hystrix
- SPRINGCLOUD(EUREKA+RIBBON+FEIGN+HYSTRIX)
- Spring Cloud Eureka自我保护机制
- springcloud(二):注册中心Eureka
- 客户端负载均衡Ribbon之一:Spring Cloud Netflix负载均衡组件Ribbon介绍
- Spring Cloud中各组件超时总结
- 嗡汤圆的Spring Cloud自学(PART.2):eureka服务注册与代理端使用
- Spring Cloud--Honghu Cloud 分布式微服务云系统-Eureka(六)
- spring-cloud的eurekaserver启动报错找不到主类
- spring cloud学习——12. Service Discovery: Eureka Server
- Spring Cloud源码分析(一)Eureka
- Spring Cloud Eureka 增加权限认证
- spring-cloud 注册中心eureka环境搭建
- spring cloud-eureka