0511-java study notes

1.springmvc principle

img

1. The user sends a request to the front-end controller DispatcherServlet (also called the central processor).
2. DispatcherServlet receives the request and calls the HandlerMappering processor mapper
. 3. The processor mapper finds the specific processor (can be searched based on xml configuration and annotations) ), generate the processor object and processor interceptor (generated if any) and return them to DispatcherServlet.
4. DispatcherServlet calls HandlerAdapter processor adapter.
5.HandlerAdapter calls the specific processor (Controller, also called back-end controller) through adaptation.
6. After the Controller execution is completed, it returns to ModelAndView.
7. The HandlerAdapter returns the controller execution result ModelAndView to the DispatcherServlet.
8. DisPatcherServlet passes the ModelAndView to the ViewReslover view parser.
9. ViewReslover returns the specific View after parsing.
10. DispatcherServlet renders the view based on the View (that is, fills the model data into the view).
11.DispatcherServlet responds to the user.

3.What are the core annotations of springboot and the annotations commonly used in projects? Such as @controller, @service, etc.

  1. SpringBootConfiguration

  2. ComponentScan

  3. EnableAutoConfiguration

@Data: Entity classes do not need to manually add get set methods

@NoArgsConstructor: Automatically generate parameterless constructor

@AllArgsConstructor: Automatically generate all-parameter constructors

@Mapper

Used in the KoneLogsMapper file to mark the file as a mapper file

The difference between @Select and @SelectProvider

Write the SQL statement directly after @Select

@Select("SELECT * FROM ***_logs WHERE cardtype=#{cardType} AND cardid=#{cardId} AND " +
"NOT isdeleted ORDER BY date,fromtime ")

Reference file after @SelectProvider

@SelectProvider(type = ******Provider.class, method = “selectParam”)
KoneLogsData findById(@Param(“id”) Integer id);

@Service

Mark this layer as a Service file

@Autowired

Automatically import corresponding files

@ExceptionCatcher("Failed to add log!")

Exception prompt thrown

@ApiIgnore

The project inherits swagger for viewing the test interface. @ApiIgnore is to make the annotation ignore this API.

The difference between @Controller and @RestController

The @RestController annotation is equivalent to the combined effect of @ResponseBody + @Controller.

  1. If you just annotate the Controller with @RestController, the method in the Controller cannot return the jsp page or HTML. The configured view resolver InternalResourceViewResolver does not work, and the returned content is the content in Return.

  2. If you need to return to the specified page, you need to use @Controller with the view resolver InternalResourceViewResolver.
    If you need to return JSON, XML or custom mediaType content to the page, you need to add the @ResponseBody annotation to the corresponding method.

The difference between @RequestBody and @RequestParam

@RequestBody is mainly used to accept data in the json string passed from the front end to the back end (data in the request body); the GET method does not have a request body, so when using @RequestBody to receive data, the front end cannot use the GET method to submit data, but must Submit using POST method. In the same receiving method on the backend, @RequestBody and @RequestParam() can be used at the same time. There can be at most one @RequestBody, but there can be multiple @RequestParam().

Note: If @RequestParam(xxx) is written before the parameter, then the front end must have the corresponding xxx name (regardless of whether it has a value, of course you can adjust whether it must be passed
by required attribute of the annotation), if there is no xxx If so, then the request will go wrong and 400 will be reported.

@PostMapping(“addLog”)

Post method accepts the request body,

@GetMapping(“deleteLog”)

Get method accepts parameters

@MapperScan (use this annotation in the springBoot startup file to scan Mapper files)

@MapperScan(basePackages = “com.****e.dao”)

@EnableScheduling

Spring’s own scheduled task function @EnableScheduling

The difference between @Component and @ComponentScan

The purpose of using @Component and @ComponentScan is different. Using the @Component annotation on a class indicates that the annotated class is a candidate class when a class needs to be created. Like a show of hands.

@ComponentScan is used to scan classes under the specified package. It’s like seeing who has raised their hands.

@SpringBootApplication

The source code contains @ComponentScan, @EnableAutoConfiguration, @SpringBootConfiguration

@EnableAutoConfiguration, this annotation has the same function as @Configuration, both are used to declare that the current class is a configuration class.

@EnableAutoConfiguration is the core annotation for springboot to realize automatic configuration. Through this annotation, the beans required by the spring application are injected into the container.

4.springcloud core components

1.Eureka:

1. Eureka server: ** Also known as the service registration center, like other service registration centers, it supports high-availability configuration. If Eureka is deployed in cluster mode, when a shard in the cluster fails, Eureka will enter self-protection mode. It allows the discovery and registration of services to continue during a shard failure. When the failed shard comes back up, other shards in the cluster will synchronize their state back again.

2. Eureka client: ** Mainly handles the registration and discovery of services. The client service is embedded in the code of the client application through annotations and parameter configuration. When the application is running, the Eureka client registers the services it provides with the registration center and periodically sends heartbeats to update its service lease. . At the same time, it can also query the currently registered service information from the server and cache them locally and refresh the service status periodically.

3. The high availability of Eureka Server** actually means registering itself as a service to other registration centers, so that a group of mutually registered service registration centers can be formed to achieve mutual synchronization of service lists and achieve high availability.

2.ribbon

Ribbon is a client load balancer based on HTTP and TCP. It can poll the server list through the ribbonServerList configured in the client to achieve service balancing. When Ribbon and Eureka are used together, Ribbon's service instance list RibbonServerList will be rewritten by DiscoveryEnabledNIWSServerList and expanded to obtain the server list from the Eureka registration center. At the same time, it will also use NIWSDiscoveryPing to replace IPing, which delegates the responsibility to Eureka to determine whether the server has been started.

In client load balancing, all client nodes maintain a list of servers they want to access, and the lists of these servers come from the service registration center (such as Eureka). In client load balancing, heartbeats are also needed to maintain the health of the server list, but this step needs to be completed in cooperation with the service registration center.

Through the encapsulation of Spring Cloud Ribbon, we only need the following two steps to use client load balancing calls in the microservice architecture:

1. The service provider only needs to start multiple service instances and register them in one registration center or multiple associated service registration centers.

2. The service consumer directly implements service-oriented interface calls by calling the RestTemplate modified by the @LoadBalanced annotation.

3.feign

The key mechanism of Feign is the use of dynamic agents

1. First, if the @FeignClient annotation is defined for an interface, Feign will create a dynamic proxy for this interface.

2. When calling the interface, the essence is to call the dynamic proxy created by Feign.

3. Feign's dynamic proxy will dynamically construct the address of the service to be requested based on the @RequestMapping and other annotations on the interface.

4. For this address, initiate a request and parse the response

Feign works closely with Ribbon and Eureka

1. First, Ribbon will obtain the corresponding service registry from Eureka Client, and then know which machines all services are deployed on and which ports they are listening on.

2. Then Ribbon can use the default Round Robin algorithm to select a machine.

3. Feign will construct and initiate a request for this machine.

4.Hystrix

In the microservice architecture, there are so many service units. If one unit fails, it is easy to cause the failure to spread due to dependencies, eventually leading to the paralysis of the entire system. This kind of architecture is more unstable than the traditional architecture. In order to solve such problems, a series of service protection mechanisms such as circuit breakers have been developed.

In a distributed architecture, when a service unit fails, an error response is returned to the caller through fault monitoring of the circuit breaker instead of waiting for a long time. This will prevent threads from being occupied for a long time due to calling faulty services and avoid the spread of faults in the distributed system.

Hystrix has powerful functions such as service degradation, service circuit breaker, thread and signal isolation, request caching, request merging and service monitoring.

Hystrix uses the bulkhead mode to implement thread pool isolation. It creates an independent thread pool for each dependent service. In this way, even if the delay of a dependent service is too high, it will only affect the call of the dependent service. Will not slow down other dependent services

5. Zuul

Spring Cloud Zuul integrates with Spring Cloud Eureka, registers itself as an application under Eureka service governance, and obtains instance information of all other microservices from Eureka.

For the maintenance of routing rules, Zuul will create a routing map by using the service name as the ContextPath by default.

Zuul provides a set of filter mechanisms that can support unified calls without attachment to the API gateway to perform pre-filtering of microservice interfaces, and has implemented interception and verification of microservice interfaces.

Summarize:

Eureka: When each service starts, Eureka Client will register the service to Eureka Server, and EurekaClient can also pull the registry from Eureka Server in turn to know where other services are.

Ribbon: When a request is initiated between services, load balancing is performed based on Ribbon, and one machine is selected from multiple machines of a service.

Feign: Feign-based dynamic proxy mechanism, based on the annotation and selected machine, splices the request URL address and initiates the request

Hystrix: Requests are initiated through the thread pool of Hystrix. Different services use different thread pools, which realizes the isolation of different service calls and avoids the problem of service avalanche.

Zuul: If the front-end or mobile terminal wants to call the back-end system, it will be entered through the Zuul gateway, and the Zuul gateway will forward the request to the corresponding service.

5. Singleton mode

Lazy-style singleton, hungry-style singleton, and registered singleton. The singleton
pattern has the following characteristics:
  1. A singleton class can only have one instance.
  2. A singleton class must create its own unique instance.
  3. The singleton class must provide this instance to all other objects.

おすすめ

転載: blog.csdn.net/qq_44794782/article/details/116674915