在微服务领域Spring Boot自动伸缩如何实现
- - IT瘾-tuicool自动伸缩是每个人都想要的,尤其是在微服务领域. 让我们看看如何在基于Spring Boot的应用程序中实现. 我们决定使用 Kubernetes、 Pivotal Cloud Foundry或 HashiCorp's Nomad等工具的一个更重要的原因是为了让系统可以自动伸缩. 当然,这些工具也提供了许多其他有用的功能,在这里,我们只是用它们来实现系统的自动伸缩.
org.springframework.boot
spring-boot-starter-actuator
management.endpoint.metrics
设置为 true
。现在,您可以通过调用 GET /actuator/metrics
来检查度量指标的完整列表。对我们来说,最重要的指标之一是 http.server.requests
,它展示了请求数量和响应时间的统计信息,并会自动记录下请求类型(POST、GET等)、HTTP状态码和uri。
io.micrometer
micrometer-registry-influx
management:
metrics:
export:
influx:
db: springboot
uri: http://192.168.99.100:8086
management.endpoint.metrics
为 true
io.micrometer
micrometer-registry-prometheus
scrape_configs:
- job_name: 'springboot'
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['person-service:2222']
@Configuration
class ConfigurationMetrics {
@Value("\${spring.application.name}")
lateinit var appName: String
@Value("\${NAMESPACE:default}")
lateinit var namespace: String
@Value("\${HOSTNAME:default}")
lateinit var hostname: String
@Bean
fun tags(): MeterRegistryCustomizer {
return MeterRegistryCustomizer { registry ->
registry.config().commonTags("appName", appName).commonTags("namespace", namespace).commonTags("pod", hostname)
}
}
}
http.server.requests
指标。
com.github.piomin
logstash-logging-spring-boot-starter
1.2.2.RELEASE
logging.logstash:
enabled: true
url: 192.168.99.100:5000
logstash-logging-spring-boot-starter
之后,你就可以使用Logstash中的日志标记功能。下图是来自Kibana中的单条日志记录的截图。
org.springframework.cloud
spring-cloud-starter-sleuth
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
@Configuration
@EnableSwagger2
public class ConfigurationSwagger {
@Autowired
Optional build;
@Bean
public Docket api() {
String version = "1.0.0";
if (build.isPresent())
version = build.get().getVersion();
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo(version))
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("(/components.*)"))
.build()
.useDefaultResponseMessages(false)
.forCodeGeneration(true);
}
@Bean
public UiConfiguration uiConfig() {
return UiConfigurationBuilder.builder().docExpansion(DocExpansion.LIST).build();
}
private ApiInfo apiInfo(String version) {
return new ApiInfoBuilder()
.title("API - Components Service")
.description("Managing Components.")
.version(version)
.build();
}
}
org.springframework.cloud
spring-cloud-starter-circuitbreaker-resilience4j
Resilience4JCircuitBreakerFactory
。以下示例使用默认值。 @Bean
public Customizer defaultCustomizer() {
return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
.timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofSeconds(5)).build())
.circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
.build());
}
org.springframework.boot
spring-boot-maven-plugin
build-info
pl.project13.maven
git-commit-id-plugin
false
/info
端点来显示所有有趣的数据。 management.endpoint.info.enabled: true
de.codecentric
spring-boot-admin-starter-server
2.1.6
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
@EnableAdminServer
注解来启用Spring Boot Admin。 @SpringBootApplication
@EnableDiscoveryClient
@EnableAdminServer
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
/info
端点和从其他Actuator端点收集到的数据。
org.springframework.cloud
spring-cloud-starter-contract-verifier
test
org.springframework.cloud
spring-cloud-starter-contract-stub-runner
test
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'GET'
urlPath('/persons/1')
}
response {
status OK()
body([
id: 1,
firstName: 'John',
lastName: 'Smith',
address: ([
city: $(regex(alphaNumeric())),
country: $(regex(alphaNumeric())),
postalCode: $(regex('[0-9]{2}-[0-9]{3}')),
houseNo: $(regex(positiveInt())),
street: $(regex(nonEmpty()))
])
])
headers {
contentType(applicationJson())
}
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@AutoConfigureStubRunner(ids = {"pl.piomin.services:person-service: :stubs:8090"}, consumerName = "letter-consumer", stubsPerConsumer = true, stubsMode = StubsMode.REMOTE, repositoryRoot = "http://192.168.99.100:8081/artifactory/libs-snapshot-local")
@DirtiesContext
public class PersonConsumerContractTest {
@Autowired
private PersonClient personClient;
@Test
public void verifyPerson() {
Person p = personClient.findPersonById(1);
Assert.assertNotNull(p);
Assert.assertEquals(1, p.getId().intValue());
Assert.assertNotNull(p.getFirstName());
Assert.assertNotNull(p.getLastName());
Assert.assertNotNull(p.getAddress());
Assert.assertNotNull(p.getAddress().getCity());
Assert.assertNotNull(p.getAddress().getCountry());
Assert.assertNotNull(p.getAddress().getPostalCode());
Assert.assertNotNull(p.getAddress().getStreet());
Assert.assertNotEquals(0, p.getAddress().getHouseNo());
}
}
org.springframework.boot
spring-boot-starter-parent
2.2.1.RELEASE
org.springframework.cloud
spring-cloud-dependencies
Hoxton.RELEASE
pom
import
原文链接: https://piotrminkowski.com/201 ... ices/