首页 > 其他分享 >微服务构建

微服务构建

时间:2022-12-12 16:35:53浏览次数:26  
标签:服务 hello public json mvc 构建 id


  • 创建一个普通的spring boot项目,添加如下控制器
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index() {
return "Hello World";
}
}
  • 监控与管理 actuator
  • 在微服务脚架构中,由于部署应用数量的成倍增加,使得系统的维护复杂度大大提升。为了让运维系统能够获取各个微服务应用的相关指标以及实现一些常规操作控制,我们需要开发一套专门用于植入各个微服务应用的接口供监控系统采集信息。actuator可以有效地省去或大大减少监控系统在采集应用指标时的开发量。
  • 快速入门
  • 新增依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 重启应用
可以看到控制台有如下输出:
2017-11-0409:59:38.642  INFO 12484 --- [           main]o.s.b.a.e.mvc.EndpointHandlerMapping    : Mapped "{[/trace ||/trace.json],methods=[GET],produces=[application/json]}" onto public java.lang.Objectorg.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/dump ||/dump.json],methods=[GET],produces=[application/json]}" onto publicjava.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped"{[/metrics/{name:.*}],methods=[GET],produces=[application/json]}"onto public java.lang.Objectorg.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/json]}"onto public java.lang.Objectorg.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-0409:59:38.642 INFO 12484 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/autoconfig ||/autoconfig.json],methods=[GET],produces=[application/json]}" onto publicjava.lang.Objectorg.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mappings ||/mappings.json],methods=[GET],produces=[application/json]}" onto publicjava.lang.Objectorg.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-04 09:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/beans ||/beans.json],methods=[GET],produces=[application/json]}" onto publicjava.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/info ||/info.json],methods=[GET],produces=[application/json]}" onto public java.lang.Objectorg.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/json]}"onto public java.lang.Objectorg.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped"{[/env/{name:.*}],methods=[GET],produces=[application/json]}" ontopublic java.lang.Objectorg.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env ||/env.json],methods=[GET],produces=[application/json]}" onto publicjava.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2017-11-0409:59:38.642 INFO 12484 --- [ main]o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/health ||/health.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot
这些端点是actuator模块根据应用依赖和配置自动创建出来的监控和管理端点
访问端点:
http://localhost:8080/health
{
"status":"UP",
"diskSpace":{
"status": "UP",
"total": 314571747328,
"free": 296483340288,
"threshold": 10485760
}
}

  • 原生端点分析
  • 根据端点的作用,可以将原生端点分为以下三大类:
  • 应用配置类:获取应用程序中加载的应用配置、环境变量、自动化配置报告等与Spring Boot应用密切相关的配置类信息
  • 度量指标类:获取 应用程序运行过程中用于监控的度量指标,比如内存信息、线程池信息、HTTP请求统计等。
  • 操作控制类:提供了对应用的关闭等操作类功能。
    每个端点的详细功能不再展开
  • 服务治理 Eureka
  • 产生原因
    在最开始构建微服务系统的时候服务可能并不多,可以通过静态配置完成服务的调用,随着服务增多,难以维护,为了解决微服务架构中的服务实例维护问题产生了大量的服务治理框架和产品。这些框架和产品的实现都是围绕着服务注册与服务发现机制来完成对微服务应用实例的自动化管理。
  • 服务注册:在服务治理框架中,通常都会构建一个注册中心,每个服务单元向注册中心登记自己提供的服务,将主机与端口号、版本号、通信协议等一些附加信息告知注册中心,注册中心将服务名分类组织服务清单。比如,我们有两个提供服务A的进程分别运行于192.168.0.100:0:8000和192.168.0.101:8000位置上,另外还有三个提供服务B的进程分别运行于192.168.0.100:9000、192.168.0.101:9000、192.168.0.102:9000位置上。当这些进程均启动,并向注册中心注册自己的服务后,注册中心就会维护类似下面的一个服务清单。另外,服务注册中心还需要以心跳的方式去监测清单中的服务是否可用,若不可用需要从服务清单中剔除,达到排除故障服务的效果。
    服务名 位置
    服务A 192.168.0.100:0:8000和192.168.0.101:8000
    服务B 192.168.0.100:9000、192.168.0.101:9000、192.168.0.102:9000
  • 服务发现:由于在服务治理框架下运作,服务间的调用不再通过指定具体的实例地址来实现,而是通过向服务名发起请求调用实现。所以,服务调用方在调用服务提供方接口的时候,并不知道具体的服务实例位置。因此,调用方需要向服务注册中心咨询服务,并获取所有服务的实例清单,以实现对具体服务实例的访问。比如,现有服务C希望调用服务A,服务C就需要向注册中心发起咨询服务请求,服务注册中心就会将服务A的位置清单返回给服务C,如按上例服务A的情况,c便获得了服务A的两个可用位置192.168.0.100:0:8000和192.168.0.101:8000。当服务C要发起调用的时候,便从该清单中以某种轮询策略取出一个位置来进行服务调用,这其实就是客户端负载均衡。(具体场景会不同,不用每次都向注册中心咨询)
  • Eureka服务端
    我们也称为注册中心。依托于强一致性提供良好的服务实例可用性,可以应对多种不同的故障场景。如果Eureka以集群模式部署,当集群中有分片出现故障时,那么Eureka就转入自我保护模式。它允许在分片故障期间继续提供服务的发现和注册,当故障分片回复运行时,集群中的其他分片会把它们的状态再次同步回来。
  • Eureka客户端
    主要处理服务的注册和发现。客户端服务通过注解和参数配置的方式,嵌入在客户端应用程序的代码中,在应用程序运行时,Eureka客户端向注册中心注册自身提供的服务并周期性地发送心跳来更新它的服务租约。同时,它也能从服务端查询当前注册的服务信息并把它们缓存到本地并周期性的刷新服务状态。
  • 快速入门
  • 搭建服务注册中心
    创建一个基础的SpringBoot工程,添加如下依赖:
<dependency>

<groupId>org.springframework.cloud</groupId>

<artifactId>spring-cloud-starter-eureka-server</artifactId>

</dependency>
通过@EnableEurekaServer注解启动一个服务注册中心提供给其他应用进行对话。
@EnableEurekaServer
@SpringBootApplication
public classEurekaServerApplication {

public static voidmain(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
在默认设置下,该服务注册中心也会将自己作为客户端来尝试注册它自己,所以需要禁用:在application.properties中增加如下配置:
server.port=1111

eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
//注释
eureka.client.register-with-eureka:为false代表不向注册中心注册自己。
eureka.client.fetch-register:设置为false代表不需要去检索服务

启动应用,访问Eureka信息面板:http://localhost:1111/。现在Instancescurrently registered with Eureka栏还是空的,说明
该注册中心还没有注册任何服务。

* 注册服务提供者
打开hello项目,添加如下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
改造/hello请求处理接口,通过注入DiscoveryClient对象,在日志中打印出服务的相关内容
@RestController
public classHelloController {

@Autowired
private DiscoveryClientclient;
@RequestMapping("/hello")
public String index() {
ServiceInstanceinstance=client.getLocalServiceInstance();
System.out.println("/hello,host:"+instance.getHost()+",service_id:"+instance.getServiceId());
return "HelloWorld";
}
}
在主类中通过加上@EnableDiscoveryClient注解,激活Eureka中的DiscoveryClient实现(自动化配置,创建DiscoveryClient接口针对Eureka客户端的EurekaDiscoveryClient实例),才能实现上述Controller中对服务信息的输出。
@EnableDiscoveryClient
@SpringBootApplication
public classHelloApplication {

public static voidmain(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
在application.properties配置文件中,通过spring.application.name属性为服务命名,通过eureka.client.serviceUrl.defaultZone属性来指定注册中心的地址。

测试:
访问http://localhost:8080/hello控制台如下输出:/hello,host:LAPTOP-KETF5MDN,service_id:hello-service这些输出内容就是之前我们在HelloController中注入的DiscoveryClient接口对象,从服务注册中心获取的服务相关信息。
  • 客户端负载均衡Ribbon
  • 产生原因:
    前文已经实现了微服务的注册与发现。启动各个微服务时,Eureka client会把自己的网络信息注册到Eureka Service上。但是,这样的架构依然存在有一些问题。一般来说,在生产环境中,各个微服务都会部署多个实例。那么服务消费者要如何将请求分摊到多个服务提供者实例上呢?
  • Ribbon
    Ribbon有助于控制HTTP和TCP客户端的行为。在Spring Cloud中,当Ribbon与Eureka配合使用时,Ribbon可自动从Eureka Server获取服务提供者地址列表,并基于负载均衡算法,请求其中一个服务提供者实例。
  • 快速入门
    我们以前面的hello项目作为去取数据方,hello项目我们启动2个端口8030和8040 控制器做如下修改:
@RestController
public class HelloController {

@Autowired
private DiscoveryClient client;

@RequestMapping("/{id}")
public Stringindex(@PathVariable Long id) {
System.out.println(id);
ServiceInstance instance =client.getLocalServiceInstance();
System.out.println("/hello,host:" + instance.getHost() +",service_id:" + instance.getServiceId());
return "HelloWorld" + " Id为:" + id;
}
}
下面写一个movie去访问hello的数据
为新项目添加hello的依赖加Ribbon的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
创建Spring boot项目:

为RestTemplate添加@LoadBalanced注解,只需添加该注解,就可为RestTemplate整合Ribbon,使其具备负载均衡的能力。
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumeApplication {

@Bean
@LoadBalanced
public RestTemplaterestTemplate() {
return new RestTemplate();
}

public static voidmain(String[] args) {
SpringApplication.run(ConsumeApplication.class, args);
}
}
编写Controller:
@RestController
public class MovieController {
@Autowired
private RestTemplaterestTemplate;
@Autowired
private LoadBalancerClientloadBalancerClient;

@RequestMapping(value ="/user/{id}")
public StringfindById(@PathVariable Long id) {
System.out.println(id);
returnthis.restTemplate.getForObject("http://hello-service/" + id,String.class);
}

@RequestMapping("/log-instance")
public String logUserInstance(){
ServiceInstance serviceInstance= this.loadBalancerClient.choose("hello-service");
returnserviceInstance.getServiceId() + "," + serviceInstance.getHost() +"," + serviceInstance.getPort();
}
}
由代码可知,我们将请求的地址写为http://hello-service/。hello-service是hello微服务的虚拟主机名,当Ribbon和Eureka配合使用时,会自动将虚拟主机名映射成微服务的网络地址。在logUserInstance()方法中使用LoadBalancerClient的API更加直观地获得当前选择的微服务节点,多次访问,我们发现数据在hello-service,LAPTOP-KETF5MDN,8030和hello-service,LAPTOP-KETF5MDN,8040中切换,说明实现了负载均衡。

访问:http://localhost:8010/user/1
可以显示如下数据:Hello World Id为:1,说明能够成功访问。
  • 服务容错保护 Hystrix
  • 产生原因
    在微服务架构中,我们将系统拆分成很多服务单元,各单元的应用间通过服务注册与订阅的方式相互依赖。由于每个单元都在不同的进程中运行,依赖通过远程调用的方式执行,这样就有可能因为网络原因或是依赖服务自身问题出现调用故障或延迟,而这些问题会直接导致调用方的对外服务也出现延迟,若此时调用方的请求不断增加,最后就会因为等待出现故障的依赖方响应形成任务积压,最终导致自身服务的瘫痪。
  • Hystrix的实现原理
    当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个错误响应,而不是长时间的等待。这样就不会使得线程因调用故障服务被长时间占用不释放,避免了故障在分布式系统中的蔓延。
  • 快速入门
    修改movie项目:
    加入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
在主类上使用@EnableCircuitBreaker注解开启熔断器功能:
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumeApplication {

@Bean
@LoadBalanced
public RestTemplaterestTemplate() {
return new RestTemplate();
}

public static voidmain(String[] args) {
SpringApplication.run(ConsumeApplication.class,args);
}
}
改造服务消费方式,新增HelloService类,最后在helloService函数上增加@HystrixCommand注解来指定回调方法:
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;

@HystrixCommand(fallbackMethod= "helloFallback")
public String helloService(Longid) {
returnthis.restTemplate.getForObject("http://hello-service/" + id,String.class);
}

public StringhelloFallback(Long id) {
return "error:becausewait too long";
}
}
修改Controller:
@RestController
public class MovieController {
@Autowired
private RestTemplaterestTemplate;
@Autowired
private LoadBalancerClientloadBalancerClient;
@Autowired
private HelloServicehelloService;

@RequestMapping(value ="/user/{id}")
public StringfindById(@PathVariable Long id) {
System.out.println(id);
returnhelloService.helloService(id);
}

@RequestMapping("/log-instance")
public String logUserInstance(){
ServiceInstanceserviceInstance = this.loadBalancerClient.choose("hello-service");
returnserviceInstance.getServiceId() + "," + serviceInstance.getHost() +"," + serviceInstance.getPort();
}
}
Hystrix默认超时时间为2000毫秒,我们设置hello项目延迟大于2秒,就会触发熔断器:
修改hello中控制器:
@RestController
public class HelloController {

@Autowired
private DiscoveryClient client;

@RequestMapping("/{id}")
public Stringindex(@PathVariable Long id) throws Exception{
System.out.println(id);
Thread.sleep(30000);
ServiceInstance instance =client.getLocalServiceInstance();
System.out.println("/hello,host:" + instance.getHost() +",service_id:" + instance.getServiceId());
return "HelloWorld" + " Id为:" + id;
}
}
访问:http://localhost:8010/user/1
显示:error:because wait too long
说明熔断器已经生效


标签:服务,hello,public,json,mvc,构建,id
From: https://blog.51cto.com/u_12026373/5930799

相关文章