"In-depth practice spring Boot" read Note three: Core Technology source Code Analysis

Source: Internet
Author: User
Tags rabbitmq

Friends who are just concerned, can review the first two articles:

    • Basic application Development
    • Distributed Application Development

The last article summarizes the second part of "in-depth practice spring Boot", which summarizes the third and final part of this article. This part mainly explains the core technology source code analysis, because the length and the ability reason, the analysis will not be too detailed, the follow-up thorough research after further specialized writes the article. I hope you can get a better understanding of the features provided by spring boot from the reading Notes "3 article, and practice in the project, freeing from tedious and repetitive development.

I am also recently beginning to understand Spring Boot, plan to practice this year in the project, and then summarize some of the problems and experiences in the process to share with you. Want to study together, practice, exchange of friends, you can scan the text below the QR code, pay attention to my personal public number, thank you.

This article is mainly summarized from the following aspects:

    • Spring Boot automatic configuration implementation principle;
    • Spring Boot data access implementation principle;
    • Micro-service core technology implementation principle;
Off Topic

Chinese New Year holiday soon passed, tomorrow is going to work, I believe that we still do not have enough to eat, not enough to play, not with the family enough. This year because of personal reasons, did not go home for the new year, the most worried about the psychological or grandparents, they are more than 80, I hope they are healthy, happy to spend the final journey of life.

Anyway, we have to switch channels, return to normal work, good work, and look forward to the next year and family reunion better.

Spring Boot automatic Configuration implementation principle

Using spring boot to create a simple Web project is simple, does not require too much configuration, and writes a simple main program on the line:

@SpringBootApplicationpublic class ConfigApplication{    public static void main(String[] args) {        SpringApplication.run(ConfigApplication.class, args);}
Main program Analysis

First analyze the Run method (omit the non-critical part of the code):

Public Configurableapplicationcontext run (String ... args) {Configurableapplicationcontext context = null;        Configureheadlessproperty ();        Springapplicationrunlisteners listeners = getrunlisteners (args);        Listeners.started ();            try {applicationarguments applicationarguments = new defaultapplicationarguments (args);            Configurableenvironment environment = prepareenvironment (listeners, applicationarguments);            Banner Printedbanner = printbanner (Environment);            context = CreateApplicationContext ();            analyzers = new Failureanalyzers (context);            Preparecontext (context, environment, listeners, applicationarguments, Printedbanner);            listeners.finished (context, NULL);        return context;            } catch (Throwable ex) {handlerunfailure (context, listeners, analyzers, ex); throw new IllegalStateException (ex);        }    } 

It starts with a springapplicationrunlisteners listener, and then creates an application context Configurableapplicationcontext that loads the classes and various environment configurations required by the application.

An application can function properly, need some environment variables, various resources and some related configuration, see below the CreateApplicationContext method will load the application-defined and required classes and various resources.

Automatic configuration

All of the autoconfiguration is introduced from annotation @springbootapplication, which in fact contains @configuration, @EnableAutoConfiguration, and @componentscan, where @ Enableautoconfiguration is enabled for automatic configuration, and some auto-configured class definitions are imported.

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan(    excludeFilters = {@Filter(    type = FilterType.CUSTOM,    classes = {TypeExcludeFilter.class})})public @interface SpringBootApplication {    Class<?>[] exclude() default {};    String[] excludeName() default {};    @AliasFor(        annotation = ComponentScan.class,        attribute = "basePackages"    )    String[] scanBasePackages() default {};    @AliasFor(        annotation = ComponentScan.class,        attribute = "basePackageClasses"    )    Class<?>[] scanBasePackageClasses() default {};}

Enableautoconfiguration will eventually import a list of automatically configured classes, many of the auto-configuration classes in the list, most of which will be imported and in a standby state, and the associated functionality will be enabled when the relevant package is introduced into the project.

For example, when a Redis reference is configured in the project's MAVEN configuration, the default configuration entry for Redis is enabled, the configuration in the project is read first, the configuration defaults are enabled only if there are no related configurations in the project, and the following code is the automatic configuration of Redis, if not set in the configuration file, The following default settings are used.

@ConfigurationProperties(    prefix = "spring.redis")public class RedisProperties {    private int database = 0;    private String host = "localhost";    private String password;    private int port = 6379;    private int timeout;    private RedisProperties.Pool pool;    private RedisProperties.Sentinel sentinel;    private RedisProperties.Cluster cluster;    public RedisProperties() {    }

With automatic configuration, you do not have to define the configuration item name repeatedly, overriding the agreed configuration items. You can see which configuration items are available by looking at each of the properties classes.

Spring Boot data Access implementation principle

To use a database, you must first establish a connection to the database server. For relational databases, the Spring Boot connection data source is typically implemented in a JDBC manner. Other types of databases use their own separate ways to establish connections.

Data source Type and Driver

The JDBC connection data source must specify the data source type and the database driver, and the data source is mainly 4:

    • Use of the Java.sql.DriverManager class;
    • Using the subclass that implements the Javax.sql.DataSource interface, the DataSource interface is implemented by the driver supplier, there are 3 kinds of implementations, basic implementation, connection pool implementation, distributed transaction implementation;
    • DBCP connection pool, Apache software funds under the Open source connection pool implementation, TOMCAT connection pool is the use of this connection pool to achieve;
    • C3P0 connection pool;

Spring Boot uses Org.apache.tomcat.jdbc.pool.DataSource by default, which uses the 2nd method to implement the Javax.sql.DataSource interface. The type of the data source can be changed by configuration.

In addition, Spring Boot supports almost all existing databases by default.

Data Access function implementation

After establishing a connection with the database, it is possible to perform some access operations on the database and to implement the management functions of the database. Data access operations consist largely of two things: entity modeling and persistence.

Whether it's a relational database or a NoSQL database, it follows this design specification. Entity modeling the common objects and relationships of Java are mapped to database table machine-related relationships, in spring boot, mainly through annotations.

Relational databases use a set of JPA standards, which combine hibernate for entity persistence. Subsequent database management designs follow JPA as a standard specification, providing the same API to access the database.

Implementation principle of micro-service core technology

Spring Cloud is a set of cloud application development tools based on further encapsulation of Netfix open source components that can be used to develop a variety of microservices applications.

Configuring service Implementations

In the previous article, the online Update feature for configuration management uses the event bus, Spring-cloud-bus, to publish state changes, and to use distributed messages to publish update events, and distributed messages end up using RABBITMQ for messaging.

To review the online update process:

    • Update the GIT repository configuration file;
    • Update the request with the Post command;
    • The configuration Management Server reads the configuration file from the Git repository and distributes the configuration file to the individual clients while releasing an update message in the RABBITMQ;
    • The client subscribes to the RABBITMQ message and executes the update after receiving the message;

Message distribution in the configuration Management Server is implemented from a call to the Spring-cloud-stream component from Spring-cloud-bus, and Spring-cloud-stream uses RABBITMQ for distributed message distribution. The concrete realization does not say, has used the RABBITMQ the very good understanding.

Discovery Services and load balancing

The client performs the registration using a scheduled task, and the client updates the list of other online clients from the discovery server and uses a timed task to manage it.

When an app enables the Discovery Services feature, the Ribbon's Load Balancing service is enabled by default. The Ribbon obtains online clients through the Discovery service and establishes a load-balancing mechanism for clients with multiple instances.

Distributed messaging implementations

With Spirng-cloud-stream, you can use RABBITMQ asynchronous messages very simply, and distributed message distribution in Spring Cloud's configuration management is done by calling the Spring-cloud-stream component.

The following implementation of message producers and consumers illustrates the implementation of distributed messaging

Message producers:

@EnableBinding(Source.class)@RestController @SpringBootApplication public class SenderApplication {     @Autowired     @Output(Source.OUTPUT)     private MessageChannel channel;    @RequestMapping(method = RequestMethod.POST, path = "/send")     public void write (@RequestBody Map<String, Object> msg){        channel.send(MessageBuilder.withPayload(msg).build());    }     public static void main(String[] args) {        SpringApplication.run(SenderApplication.class, args);    

Message consumers:

@EnableBinding(Sink.class)@IntegrationComponentScan@MessageEndpoint@SpringBootApplicationpublic class ReceiverApplication {    @ServiceActivator(inputChannel=Sink.INPUT)    public void accept(Map<String, Object> msg){        System.out.println(msg.get("msg").toString() + ":" + msg.get("name"));    }    public static void main(String[] args) {        SpringApplication.run(ReceiverApplication.class, args);    }}

As can be seen from the above analysis, Spring boot and some of its related components, has tried to do some of the functions that can be achieved and done, all of us to achieve. While the use of spring boot and its associated components looks very simple, it can actually be incredibly powerful, which is the magic of spring boot and its components.

"In-depth practice spring Boot" read Note three: Core Technology source Code Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.