Review: Microservice Technology

https://yanglinwei.blog.csdn.net/article/details/103892472

SpringBoot: It is a rapid development framework that can quickly integrate third-party frameworks and simplify XML configuration. It is all in the form of annotations and has a built-in Tomcat container to help developers achieve rapid development. For development, SpringBoot's Web components integrate the SpringMVC framework by default (SpringMVC is the control layer). Requires JDK 1.8 or above, Spring Framework 4.1.5 or above.


Rendering Web pages: Use template engines, including: Thymeleaf, FreeMarker, Velocity, Groovy, Mustache


SpringBoot related notes:

  • @ExceptionHandler: Indicates intercepting exceptions;
  • **@RestController: ** Adding RestController above means modifying all methods of the Controller to return JSON format, and the Restful interface can be written directly;
  • @EnableAutoConfiguration: The function is to let Spring Boot automatically configure the Spring framework based on the dependencies declared by the application. This annotation tells Spring Boot to guess what you want based on the added jar dependencies. Configure Spring;
  • @Transactional: SpringBoot integrates transactions by default;
  • ****@Scheduled:****Create a scheduled task
  • @EnableAsync, @Async: Use multi-threading technology

SpringBoot multi-data source transaction management: Use jta+atomikos for distributed transaction management. When using JTA and Atomikos in a Spring Boot application, it is usually because your application needs to access multiple data sources at the same time, such as multiple databases. In this case, you want all database operations to either be submitted successfully or all returned. Roll to ensure data consistency.

Insert image description here

Insert image description here


Devtools tool: relies on spring-boot-devtools. The underlying principle is that two ClassLoaders are used. One Classloader loads classes that will not change (third-party Jar packages), and the other A ClassLoader loads classes that will change, called a restart ClassLoader. In this way, when there is a code change, the original restart ClassLoader is discarded and a restart ClassLoader is re-created. Since there are fewer classes to be loaded, a faster restart is achieved. time (within 5 seconds).


Actuator: It is an additional feature of spring boot, which can help you monitor and manage the application in the production environment, spring-boot-starter-actuator. The Client integrates the Actuator and then registers the collected information to the Admin-UI platform. The client configuration is as follows:

spring:
  boot:
    admin:
      client:
        url: http://localhost:8080
server:
  port: 8081
  
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: ALWAYS

Optimization suggestions for SpringBoot: Component scanning (remove @SpringBootApplication and @ComponentScan, configure on the required beans), replace the built-in tomcat with undertow, JVM size configuration (Xms: Set the initial size of the Java stack, -Xmx: Set the maximum java heap size)


SpringBoot core principle: No configuration file (pure Java)Fully annotated + built-in tomcat-embed-core to implement SpringBoot framework, the Main function is started, Maven inherits dependencies, and uses the SpringMVC annotation version to achieve no configuration effect (Spring 3 introduced annotations)


SpringBoot multiple configuration files:• bootstrap.ymlLoad firstapplication.yml and then load. bootstrap.yml is used to execute when the program boots and is used to read configuration information earlier. application.yml can be used to define application-level, application-specific configuration information, and can be used to configure public parameters to be used in subsequent modules, etc.

  • application-demo.yml (configuration in local environment)
  • application-dev.yml (configuration in development environment)
  • application-local.yml (configuration in local environment)
  • application-test.yml (configuration in test environment)
  • application-prod.yml (configuration in production environment)
  • bootstrap-demo.yml (configuration in local environment, boostrap loading is better than application)
  • bootstrap-dev.yml (configuration in development environment, boostrap loading is better than application)
  • bootstrap-local.yml (configuration in local environment, boostrap loading is better than application)
  • bootstrap-test.yml (configuration in test environment, boostrap loading is better than application)
  • bootstrap-prod.yml (configuration in production environment, boostrap loading is better than application)

**SpringBoot WebMvcConfigurer interface: WebMvcConfigurerAdapter and WebMvcConfigurer are interfaces or classes used to configure Spring MVC. In newer Spring versions, WebMvcConfigurerAdapter has been deprecated and it is recommended to use the WebMvcConfigurer interface for configuration.

  • WebMvcConfigurerAdapterIs a class that can be configured by inheriting and overriding the required methods. This provides a method similar to the template method pattern, allowing developers to focus only on the configuration items that interest them.
  • WebMvcConfigurerIt is an interface, and developers need to implement the methods in the interface, which may result in the need to implement some uninteresting methods. But through the default methods introduced in Java 8, the interface can provide some default implementations, thereby reducing the workload when implementing the interface.
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    

    /**
     * 添加类型转换器和格式化器
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
    
    
        registry.addFormatterForFieldType(LocalDate.class, new USLocalDateFormatter());
    }

    /**
     * 跨域支持
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600 * 24);
    }

    /**
     * 添加静态资源--过滤swagger-api (开源的在线API文档)
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        //过滤swagger
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        registry.addResourceHandler("/swagger-resources/**")
                .addResourceLocations("classpath:/META-INF/resources/swagger-resources/");

        registry.addResourceHandler("/swagger/**")
                .addResourceLocations("classpath:/META-INF/resources/swagger*");

        registry.addResourceHandler("/v2/api-docs/**")
                .addResourceLocations("classpath:/META-INF/resources/v2/api-docs/");

    }
    }

    /**
     * 配置消息转换器--这里我用的是alibaba 开源的 fastjson
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    
    
        //1.需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //2.添加fastJson的配置信息,比如:是否要格式化返回的json数据;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteDateUseDateFormat);
        //3处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        //5.将convert添加到converters当中.
        converters.add(fastJsonHttpMessageConverter);
    }
  @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new ReqInterceptor()).addPathPatterns("/**");
    }
}

SpringCloud: It is a very complete microservice solution framework, which includes service governance, registration center, configuration management, circuit breaker, intelligent routing, micro agent, SpringCloud contains many sub-projects such as control bus, global lock, distributed session, etc. For example:

  • Eureka (phonetic symbol: [/juˈriːkə]): Service Governance Registration Center
  • Hystrix (phonetic symbol: [hɪst’rɪks]): Service Protection Framework
  • Ribbon (phonetic symbol: [ˈrɪbən]): Client load balancer
  • Feign (phonetic symbol: [feɪn]): declarative service calling component based on ribbon and hystrix
  • Zuul (phonetic symbol: Zuul): Gateway component, providing intelligent routing, access filtering and other functions.

Eureka service consumption model and service registration model:

  • Service Consumer Model:

     获取服务:消费者启动的时候,使用服务别名,会发送一个rest请求到服务注册中心获取对应的 服务信息,然后会缓存到本地jvm客户端中,同时客户端每隔30秒从服务器上更新一次)
    
     服务下线:服务实例过正常的关闭操作时,它会触发一个服务下线的REST请求给Eureka Server, 服务端在接收到请求之后,将该服务状态置为下线(DOWN)
    
  • Service registration mode:

    失效剔除:客户端非正常下线,Eureka Server 在启动的时候会创建一个定时任多默认每隔一段时间(默认为60秒)将当前清单中超时(默认为90秒)没有续约的服务除出去;
    
    自我保护:EurekaServer在一定时间内没有收到EurekaClient发送的心跳,便会把该实例从注册服务列表中剔除(默认是90秒),但是在短时间内丢失大量的实例心跳,这时候EurekaServer会开启自我保护机制,Eureka不会踢出该服务。
    

Server core configuration:

server:
    # 测试时关闭自我保护机制,保证不可用服务及时踢出
    enable-self-preservation: false
    ##剔除失效服务间隔
    eviction-interval-timer-in-ms: 2000

Client core configuration:

# 心跳检测检测与续约时间
# 测试时将值设置设置小些,保证服务关闭后注册中心能及时踢出服务
  instance:
###Eureka客户端向服务端发送心跳的时间间隔,单位为秒(客户端告诉服务端自己会按照该规则)  
    lease-renewal-interval-in-seconds: 1
####Eureka服务端在收到最后一次心跳之后等待的时间上限,单位为秒,超过则剔除(客户端告诉服务端按照此规则等待自己)
    lease-expiration-duration-in-seconds: 2

Eureka alternatives: Consul, Eureka, Nacos, etc. Zookeeper guarantees CP (master hangs up, the election takes time, and registration is unavailable during this period), while Eureka guarantees AP (unlike zk, all nodes are equal, and the remaining nodes can still provide service registration).


Nacos: It is an open source platform for service discovery, configuration management and service governance. Eureka has stopped maintenance and it is recommended to use Nacos. In addition to service registration and discovery, Nacos also provides configuration management functions. Provides wider compatibility and can be used in containerized environments and traditional virtual machine environments.


CAP theory

  • "C" refers to consistency: That is, when a Process modifies a certain data, other Process reads this data and gets is updated data, but not all systems can do this. For example, in some systems that do not strictly require consistency, the data obtained by subsequent processes may still be the data before modification, or it may take a certain period of time to obtain the modified data. This is called "weak consistency", the most classic The application is the DNS system. When users modify the DNS configuration, it is often not updated immediately across the entire network. There must be a delay. This delay is called the "inconsistency window". Its length depends on factors such as the load of the system and the number of redundancies. But for some systems, once written, the modified data must be read later, such as bank account information. This is called "strong consistency".
  • "A" refers to Availability: That is, the system can always provide continuous service capabilities to users. When the user makes a request, the system can give a response (success or failure), and the response is given immediately instead of waiting for other things to be completed before responding. If you need to wait for something to complete before responding, then "availability" doesn't exist.
  • "P" refers to fault tolerance (Partition tolerance): Any distributed computing system is composed of multiple nodes. Under normal circumstances, communication between nodes is normal. But in some cases, the communication between nodes will be disconnected, and this disconnection is called a "Partition". Partition is very common in the implementation of distributed computing, because nodes cannot always fail, especially for mass storage systems that span physical areas, and fault tolerance can ensure that if only some nodes in the system fail If used, the related operations can still be completed normally.

Ribbon load balancer: Ribbon obtains the service registration information list from the eureka registration center server, caches it locally, and then implements the rotation load balancing strategy locally (). @LoadBalanced annotation. nginx is the server-side load balancer, and ribbon is the local load balancer. Client forwarding

@SpringBootApplication
@EnableEurekaClient
public class App {
    
    

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

    @Bean
    //@LoadBalanced
    //@LoadBalanced就能让这个RestTemplate在请求时拥有客户端负载均衡的能力(增加@LoadBalanced,就不能使用127.0.0.1,只能使用应用名)
    RestTemplate restTemplate() {
    
    
        return new RestTemplate();
    }

}

Service protection related concepts:

  • Service avalanche: The service avalanche effect occurs when services are accumulated in the same thread pool, because all requests are processed by the same thread pool. At this time, if the concurrency is high, In this case, all requests access the same interface, which may cause other services to have no threads to accept requests. This is the service avalanche effect;
  • Service downgrade: In high concurrency situations, to prevent users from waiting forever, use the service downgrade method (directly return a friendly prompt to the client and call the fallBack method); Service downgrade a>
  • Service circuit breaker: The purpose of the circuit breaker mechanism is to protect the service. In the case of high concurrency, if the request reaches a certain limit (you can set the threshold yourself) and if the traffic exceeds the set threshold, Then directly deny access to protect the current service. Use the service downgrade method to return a friendly prompt. Service circuit breaker and service downgrade are used together;
  • Service isolation: Because by default, only one thread pool will maintain all service interfaces, if a large number of requests access the same interface, reaching the default limit of the tomcat thread pool, it may This will cause other services to be inaccessible. Use service isolation mechanism (thread pool method and semaphore). The principle of using thread pools to achieve isolation is equivalent to each interface (service) having its own independent thread pool, because each thread pool does not affect each other, so that the service avalanche effect can be solved.
  • Service current limiting: Restrict interface access. Commonly used service current limiting algorithms include token buckets, leaky buckets, and counters, which can also be used to implement rough current limiting.

Hystrix: Mainly used to solve the problem of service avalanche. If there is a problem with an interface that causes blocking, multiple requests accessing it at the same time will cause the entire system to crash. Therefore, circuit breakers were proposed to solve the problem of service avalanche. The technologies used include "resource isolation (thread pool and semaphore isolation)", "downgrade mechanism (timeout, downgrade when resources are insufficient)", "circuit breaker (the failure rate reaches a threshold that automatically triggers downgrade)", and "caching". You can use Turbine to monitor Hystrix.

// 配置Hystrix断路器
feign:
  hystrix:
enabled: true

// hystrix禁止服务超时时间
hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: false

-------------------------
// 开启Hystrix断路器
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
public class App {
    
    

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

}

----------------------------
// 业务层代码
@RestController
public class ServiceBController {
    
    
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getOrder")
    public String getOrder() {
    
    
        // order 使用rpc 远程调用技术 调用 会员服务
        String memberUrl = "http://app-service-a/getMember";
        String result = restTemplate.getForObject(memberUrl, String.class);
        System.out.println("会员服务调用订单服务,result:" + result);
        return result;
    }

    @HystrixCommand(fallbackMethod = "orderToUserInfoFallback")
    @RequestMapping("/getUserInfoHystrix")
    public String orderToUserInfoHystrix() {
    
    
        System.out.println("orderToUserInfo:" + "当前线程池名称:" + Thread.currentThread().getName());
        return getOrder();
    }

    @RequestMapping("/orderToUserInfoFallback")
    public String orderToUserInfoFallback() {
    
    
        return "系统错误!!!!";
    }
}

Feign client: It is a web declarative HTTP remote calling tool that provides interfaces and annotations for calling. Feign client HTTP calling tool has integrated Ribbon load balancing client and Eureka by default.

Usage: Start class @EnableFeignClients, define interface @FeignClient


SpringCloud Config: It is one of the distributed configuration center frameworks, which can realize the unified management of the configuration files of all systems in microservices, and can also realize the configuration files. When changes occur, the system will automatically update to obtain new configurations. Commonly used distributed configuration center frameworks include:

  • Disconf (depends on zookpeer, developed by Baidu)
  • Zookpeer (guarantee real-time update of configuration file information - event notification)
  • diamond (developed by Alibaba)
  • Apollo (developed by Ctrip)
  • Redis
  • xxl-conf

SpringColud Config的原理:

Insert image description here


Zuul: A JVM-based gateway service used to build edge services in a microservice architecture. It is a reverse proxy that acts as a service gateway and is responsible for processing client requests, routing requests to different microservices, performing some filtering operations, and also providing load balancing, security authentication, monitoring and other functions.

Insert image description here

Nginx and Zuul's division:

  • Nginx usesserver load balancing for forwarding
  • Zuul depends onRibbon and eurekaAchieve local load balancing forwarding
  • Relatively speaking, Nginx is more powerful than Zuul. It can integrate other languages ​​​​such as lua scripts to achieve powerful functions. At the same time, Nginx can better resist high concurrency, and Zuul gateway is suitable for request filtering and interception.

zuul:
  routes:
    service1:
      path: /service1/**
      serviceId: service1
    service2:
      path: /service2/**
      serviceId: service2

Dubbo: It is a distributed service framework that provides high-performance and transparent RPC remote service callsPlan, and SOA service governance plan

Insert image description here

Calling process:

  • The service container is responsible for starting, loading, and running service providers.
  • When a service provider starts, it registers the services it provides with the registration center.
  • When a service consumer starts, he subscribes to the registration center for the services he needs.
  • The registration center returns the service provider address list to the consumer. If there is a change, the registration center will push the change data to the consumer based on the long connection.
  • The service consumer selects a provider to call from the provider address list based on the soft load balancing algorithm. If the call fails, it selects another provider to call.
  • Service consumers and providers accumulate the number of calls and call times in memory, and regularly send statistical data to the monitoring center every minute.

The difference between SpringCloud and Dubbo:

  • Similarities: SpringCloud and Dubbo can implement the RPC remote calling framework and implement service governance.
  • The difference: If you learn Dubbo, you need to assemble it yourself to learn other distributed solutions. On the contrary, if you learn SpringCloud, it has integrated all common distributed solutions.

SpringCloud Message Bus (Spring Bus): Connect distributed nodes with lightweight message agents. You can easily build a message bus. The messages it broadcasts will be Microservice instances in the registration center listen and consume.


SpringCloud message driver (Spring Stream): Simplifies the complexity of using message middleware for developers, allowing system developers to focus more on the development of core business logic. Currently only RabbitMQ (maven introduces spring-cloud-starter-stream-rabbit) and Kafka (maven introduces spring-cloud-starter-stream-kafka) are supported.

Insert image description here

  • Source: When we need to send a message, we need to pass the Source. The Source will serialize the message (POJO object) we want to send (converted to JSON format by default) String), and then send these data to the Channel;
  • Sink: When we need to monitor messages, we need to use Sink. Sink is responsible for obtaining messages from the message channel and deserializing the messages into message objects (POJO objects). Then hand it over to specific message monitoring processing for business processing;
  • Channel: The message channel is one of the abstractions of Stream. Usually when we send or listen to messages to the message middleware, we need to specify the topic/message queue name, but once we need to change the topic name, we need to modify the message sending or message listening code, but through Channel abstraction, our The business code only needs to implement the Channel. The specific theme that this Channel corresponds to can be specified in the configuration file. In this way, when the theme changes, we do not need to make any modifications to the code, thereby achieving the same message as the specific one. Decoupling of middleware;
  • Binder: Another abstraction layer in Stream. Integration with different message middleware can be achieved through different Binders. For example, in the above example, we use Binder for Kafka. Binder provides a unified message sending and receiving interface, so that we can deploy different message middleware according to actual needs. , or adjust our configuration according to the message middleware deployed in actual production.

SpringSecurity: A security framework that can provide declarative security access control solutions for Spring-based enterprise application systems. Spring Security provides several filters that can intercept Servlet requests and forward these requests to the authentication and access decision manager for processing, thereby enhancing security. Security plays many back-end roles in many companies, such as:

  • permissions framework
  • Authorization authentication oauth2.0
  • Security protection (preventing cross-site requests)
  • Session attack
  • Easy to integrate SpringMVC
  • 。。。
// Security 配置
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
  @Autowired
  private MyAuthenticationFailureHandler failureHandler;
  @Autowired
  private MyAuthenticationSuccessHandler successHandler;
	// 配置认证用户信息和权限
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
		// 添加admin账号
		auth.inMemoryAuthentication().withUser("admin").password("123456").
		authorities("showOrder","addOrder","updateOrder","deleteOrder");
		// 添加userAdd账号
		auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
		// 如果想实现动态账号与数据库关联 在该地方改为查询数据库

	}

	// 配置拦截请求资源
	protected void configure(HttpSecurity http) throws Exception {
    
    
		// 如何权限控制 给每一个请求路径 分配一个权限名称 让后账号只要关联该名称,就可以有访问权限
		http.authorizeRequests()
		// 配置查询订单权限
		.antMatchers("/showOrder").hasAnyAuthority("showOrder")
		.antMatchers("/addOrder").hasAnyAuthority("addOrder")
		.antMatchers("/login").permitAll()
		.antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
		.antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
		.antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").
		successHandler(successHandler).failureHandler(failureHandler)
		.and().csrf().disable();
	}

	@Bean
	public static NoOpPasswordEncoder passwordEncoder() {
    
    
		return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
	}

}

Several core classes of SpringSecurity:

  • **Authentication:** is an interface used to represent user authentication information. Before user login authentication, the relevant information will be encapsulated into an object of the Authentication specific implementation class. After the login authentication is successful, a more comprehensive information will be generated, including Authentication object of user permissions and other information, and then save it in the SecurityContext held by SecurityContextHolder for subsequent program calls, such as identification of access permissions, etc.
  • SecurityContextHolder: is used to save SecurityContext. The SecurityContext contains detailed information about the user currently accessing the system.
  • ****AuthenticationManager and AuthenticationProvider: ****AuthenticationManager is an interface used to handle authentication (Authentication) requests. The default implementation of AuthenticationManager is ProviderManager, and it does not directly handle authentication requests itself, but delegates it to its configured AuthenticationProvider list, and then each AuthenticationProvider will be used for authentication in turn. If the authentication result of an AuthenticationProvider is not null, it means that the AuthenticationProvider has been successfully authenticated, and subsequent AuthenticationProviders will no longer continue authentication.
  • UserDetailService: During login authentication, Spring Security will obtain the corresponding UserDetails through the loadUserByUsername() method of UserDetailsService for authentication. After the authentication is passed, the UserDetails will be assigned to the authenticated Authentication. principal, and then store the Authentication in the SecurityContext. If you need to use user information later, you can obtain the Authentication principal stored in the SecurityContext through the SecurityContextHolder.
  • GrantedAuthority: Each GrantedAuthority object represents a permission granted to the current user. GrantedAuthority is an interface, which is usually loaded through UserDetailsService and then assigned to UserDetails.

Basic authentication: It is a simple HTTP authentication method. It is an access control mechanism based on user name and password. In Basic authentication, the client appends the username and password to the HTTP request header in Base64 encoding and sends them to the server. Although Base64 encoding can prevent clear text transmission, it is not an encryption method, so in cases where security requirements are high, the HTTPS protocol should be used to encrypt communications.

The format of the Basic authentication HTTP request header is as follows:

Authorization: Basic base64EncodedCredentials

Bear authentication: It is another common HTTP authentication method, usually used in the OAuth 2.0 authorization process. A Bearer token (Token) is a credential used to access protected resources and is issued by an authorization server. The principle of Bearer authentication is that the client carries a valid Bearer token in the request, and the server verifies the validity of the token to authorize the request.

The format of the HTTP request header for Bearer authentication is as follows:

Authorization: Bearer access_token

RBAC permission model: Role-Based Access Control is widely used as a promising alternative to traditional access control (discretionary access, mandatory access). focus on.

Insert image description here


OAuth2.0: OAuth (Open Authorization) is an open standard that allows users to authorize third-party websites to access their information stored on another service provider without requiring Anything that provides usernames and passwords to third-party websites or shares their data.

Insert image description here

The OAuth authentication and authorization process is as follows:

  1. The user visits a third-party website and wants to operate certain resources stored by the user in the service provider.
  2. The third-party website requests a temporary token from the service provider.
  3. After the service provider verifies the identity of the third-party website, it grants a temporary token.
  4. After the third-party website obtains the temporary token, it directs the user to the service provider's authorization page to request user authorization. In the process, the temporary token and the return address of the third-party website are sent to the service provider.
  5. Users enter their username and password on the service provider's authorization page to authorize third-party websites to access the corresponding resources.
  6. After successful authorization, the service provider will direct the user to the return address of the third-party website.
  7. The third-party website obtains the access token from the service provider based on the temporary token.
  8. The service provider grants third-party website access tokens based on the token and user authorization.
  9. The third-party website uses the obtained access token to access the corresponding user resources stored in the service provider.

Distributed link tracing: In order to implement request tracing, when a request is sent to the entry endpoint of the distributed system, the service tracing framework only needs to create a unique trace for the request. At the same time, when circulating within the distributed system, the framework always keeps passing the unique identifier until it is returned to the requester. This unique identifier is the Trace ID mentioned above. Through the recording of Trace ID, we can correlate the logs of all request processes. Spring Cloud Sleuth and Zipkin provide distributed service link monitoring solution.


SpringColud related technology stack arrangement:
Insert image description here

Guess you like

Origin blog.csdn.net/qq_20042935/article/details/134606791