idea版本
2021.01.02
例子涉及
1.Employee Service:负责拉取员工的数据。
2.Api-Gateway:Employee Service的网关层。
3.Eureka Server : 负责服务发现和服务注册。
涉及技术
- java 1.8
- spring tool suite
- spring cloud
- spring boot
- spring rest
- maven
创建 Employee Service
1.通过Spring boot initializer ,添加 Eureka Discovery
、Actuaotr
、Web
、Rest Repositories
依赖,创建项目:
2.build.gradle
的内容:
plugins {
id 'org.springframework.boot' version '2.5.1'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'idea'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenLocal()
maven { url "https://maven.aliyun.com/nexus/content/groups/public/"}
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
maven { url 'https://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}
ext {
set('springBootAdminVersion', "2.3.1")
set('springCloudVersion', "2020.0.3")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'de.codecentric:spring-boot-admin-starter-client'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom "de.codecentric:spring-boot-admin-dependencies:${springBootAdminVersion}"
}
}
3.EmployeeServiceApplication
添加下面的代码:
package com.example.employeeservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication
public class EmployeeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeServiceApplication.class, args);
}
}
4.EmployeeServiceApplication
类
package com.example.employeeservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class EmployeeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeServiceApplication.class, args);
}
}
5.EmployeeServiceController
类
package com.example.employeeservice;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class EmployeeServiceController {
private static final Map<Integer, Employee> employeeData = new HashMap<Integer, Employee>() {
private static final long serialVersionUID = -3970206781360313502L;
{
put(111, new Employee(111, "Employee1"));
put(112, new Employee(112, "Employee2"));
}
};
@RequestMapping(value = "/findEmployeeDetails/{employeeId}", method = RequestMethod.GET)
public Employee getEmployeeDetails(@PathVariable int employeeId) {
System.out.println("Getting Employee details for " + employeeId);
Employee employee = employeeData.get(employeeId);
if (employee == null) {
employee = new Employee(0, "N/A");
}
return employee;
}
}
6.application.properties
的配置:
server.port=8011
# 表示 Eureka Server 在接收到上一个心跳之后等待下一个心跳的秒数(默认 90 秒),若不能在指定时间内收到心跳,则移除此实例,并禁止此实例的流量
# 此值设置太长,即使实例不存在,流量也能路由到该实例
# 此值设置太小,由于网络故障,实例会被取消流量
# 需要设置为至少高于 lease-renewal-interval-in-seconds 的值,不然会被误移除了
eureka.instance.lease-renewal-interval-in-seconds=12
# 表示 Eureka Client 向 Eureka Server 发送心跳的频率(默认 30 秒),如果在 lease-expiration-duration-in-seconds 指定的时间内未收到心跳,则移除该实例
eureka.instance.lease-expiration-duration-in-seconds=10
# 表示此实例是否注册到 Eureka Server 以供其他实例发现.
# 在某些情况下,如果你不想自己的实例被发现,而只想发现其他实例,配置为 false 即可.
eureka.client.register-with-eureka=false
# 表示客户端是否从Eureka Server获取实例注册信息
eureka.client.fetch-registry=false
# 表示客户端需要注册的Eureka Server的地址
eureka.client.service-url.defaultZone= http://localhost:8761/eureka/
# 开启健康检查(需要spring-boot-starter-actuator依赖)
eureka.client.healthcheck.enabled= true
# 在注册中心中显示的服务注册名称
spring.application.name=employee-service
# 是否启用/env接口
management.endpoint.env.enabled=true
spring.boot.admin.client.url=http://localhost:8761/admin
logging.level.com.example.employeeservice =debug
7.启动,浏览器访问:http://localhost:8011/findEmployeeDetails/111
{"name":"Employee1","id":111}
API-Gateway 和 Hystrix
1.添加依赖: Eureka Discovery, Actuator, Web, Hystrix, Hystrix Dashboard, Rest repositories
2.0 <= spring boot <= 2.4
2.ApiGatewayApplication
文件:
package com.example.apigateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@SpringBootApplication
@EnableEurekaClient
@EnableHystrixDashboard
@EnableCircuitBreaker
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
3.EmployeeController
文件:
package com.example.apigateway;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class EmployeeController {
@Autowired
RestTemplate restTemplate;
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@RequestMapping(value = "/employeeDetails/{employeeid}", method = RequestMethod.GET)
@HystrixCommand(fallbackMethod = "fallbackMethod")
public String getStudents(@PathVariable int employeeid)
{
System.out.println("Getting Employee details for " + employeeid);
String response = restTemplate.exchange("http://employee-service/findEmployeeDetails/{employeeid}",
HttpMethod.GET, null, new ParameterizedTypeReference<String>() {}, employeeid).getBody();
System.out.println("Response Body " + response);
return "Employee Id - " + employeeid + " [ Employee Details " + response+" ]";
}
public String fallbackMethod(int employeeid){
return "Fallback response:: No employee details available temporarily";
}
}
4.application.properties
:
server.port=8010
eureka.instance.lease-renewal-interval-in-seconds=12
eureka.instance.lease-expiration-duration-in-seconds=10
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone= http://localhost:8761/eureka/
eureka.client.healthcheck.enabled= true
spring.application.name=api-gateway
spring.boot.admin.client.url=http://localhost:8761/admin
logging.level.com.example.employeeservice=debug
5.build.gradle
plugins {
id 'org.springframework.boot' version '2.3.12.RELEASE'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
ext {
set('springBootAdminVersion', "2.3.1")
set('springCloudVersion', "Hoxton.SR11")
}
dependencies {
implementation 'de.codecentric:spring-boot-admin-starter-client'
implementation 'org.springframework.boot:spring-boot-starter-data-rest'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-hystrix'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-hystrix-dashboard'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom "de.codecentric:spring-boot-admin-dependencies:${springBootAdminVersion}"
}
}
test {
useJUnitPlatform()
}
6.浏览器访问:http://localhost:8010/employeeDetails/111
Eureka Server
1.添加依赖: Eureka Server, Actuator, Web, Spring Boot Admin Server
。
2.新建 boostrap.yml
文件:
spring:
application:
name: Eureka-Server
cloud:
config:
uri:${CONFIG_SERVER_URL:http://localhost:8888}
3.application.properties
:
server.port=${PORT:8761}
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.registry-fetch-interval-seconds=5
eureka.client.service-url.defaultZone=${DISCOVERY_URL:http://localhost:8761}/eureka/
eureka.instace.leaseRenewalIntervalInSeconds=10
management.security.enabled=false
spring.boot.admin.context-path=/admin
4.EurekaServerApplication
文件:
package com.example.eurekaserver;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
@EnableAdminServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
5.build.gradle
plugins {
id 'org.springframework.boot' version '2.3.12.RELEASE'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
ext {
set('springBootAdminVersion', "2.3.1")
set('springCloudVersion', "Hoxton.SR11")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'de.codecentric:spring-boot-admin-starter-server'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
dependencyManagement {
imports {
mavenBom "de.codecentric:spring-boot-admin-dependencies:${springBootAdminVersion}"
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
test {
useJUnitPlatform()
}
6.访问:http://localhost:8761/admin/applications