preface

In the last few days I’ve taken the time to add several new features to the code Generator (expected to be released tonight). It now supports postgresQL database, HikariCP connection pool and Swagger2. Postgresql/mysql/HikariCP/Druid/Swagger2 / swagger2 Let’s have a look.

PostgreSql VS MySql

MySQL is known as the most popular database server in the world. It is small in size, fast in speed, free in open source, strong in portability and easy to use. These characteristics make it the first database of Domestic Internet enterprises. 08 MySQL by SUN company acquisition and has been for everybody to use free, it was also at that time, MySQL accumulated tens of thousands of fans, enterprise and therefore has trained a large number of skilled use of MySQL programmers, although the PG has many advanced features, but most of the Internet, the Internet need characteristics of fast, PG does not. History has continued to create today’s situation. It can be said that the Internet made MySQL.

Ten years after SUN was acquired by ORACLE and MySql was taken over by ORACLE, MySql is still one of the most popular databases for developers today.

Compared with MySql, PG may be unfamiliar to you, PG claims to be the most advanced database server in the world, one of the most popular, one of the most advanced, you fine taste.

PG is currently maintained by over 1,000 top Internet developers, updated relatively quickly, and is completely open source and free. PG is more like an integrated database that combines the advantages of both relational and non-relational databases, allowing you to store data structures flexibly.

In addition, properties such as data consistency and integrity are a high priority for PG, which is why many projects in Japan use PG instead of MySQL. This saves a lot of trouble with transaction control, such as common concurrent updates, which PG can guarantee are correct because the hidden column holds the version field. It basically helps you implement optimistic locking without having to code it, whereas MySql has to manually implement locking. In addition, PG has its irreplaceable advantages for geographic location information storage, and external tables are also an exciting feature. Anyway, to be fair, PG is much more powerful than Mysql! It is slowly rising, believe that in the future will maintain a relatively balanced state with MySql.

In terms of running mode, PG is process mode and MySQL is thread mode. In general, process mode provides higher resource utilization in a multi-CPU environment. Process mode data sharing needs to use shared memory, while thread mode data itself is shared in the process space, different threads for data access needs to control synchronization between threads. Thread mode consumes less resources, so in theory MySql supports more connections than PG, but pgPool is an excellent connection pool software to solve this problem!

Finally, one caveat: Neither PostgreSQL nor MySQL can claim to be better than the other. For users, there is only the right one, not the best one.

HikariCP VS Druid

Druid connection pool is an open source database connection pool component. In recent years, KO has dropped the old C3P0, DBCP, become a new favorite of database connection pool, because of its simple use, security, fast speed, powerful and rich monitoring features, so many enterprises use it. Druid’s connection pool is fairly balanced, enough for most applications, and comes with a monitoring interface, which is also nice.

If the Druid connection pool fails, the connection to the Druid server will not be released. If the Druid connection pool fails, the connection to the Druid server will not be released. If the Druid connection pool fails, the Druid connection pool will fail.

<! -- Whether to recycle when time limit is exceeded -->
<property name="removeAbandoned" value="true" />
<! -- Timeout period; The unit is second. 180 seconds =3 minutes -->
<property name="removeAbandonedTimeout" value="180" />
<! An error log was generated when abanded connection was closed -->
<property name="logAbandoned" value="true" />   
Copy the code

After locating the problem and solving it, comment it out, because it will cost more performance, and be careful to use it in production environment!

HikariCP, an upstart, claims to be the fastest database connection pool, so fast that SpringBoot2 has adopted it as the default connection pool. The code size is only 130KB, as the saying goes, the concentration is the essence, it seems to be true.

HikariCP is not only a block, but also has a good reputation for stability and reliability. The author optimized and streamlined the bytecode, and used FastList instead of ArrayList to bring strong performance support.

If you’re looking for extreme performance, consider using HikariCP!

Swagger2

Swagger2 can help us generate the description of the interface document, which is conducive to the communication between the front and back staff, thus improving the work efficiency.

The usage method of Swagger2 is extremely simple. Here, taking Springboot project as an example, we first need to introduce POM dependency:

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.8.0</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.8.0</version>
</dependency>
Copy the code

Then create the corresponding configuration class:

@Configuration
// Enable swagger2
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // Enable or not (true enable false hide. Production environment recommended hidden)
                .enable(true)
                .select()
                // Set basePackage to include all methods in the package marked by @api as apis
                .apis(RequestHandlerSelectors.basePackage("testUp.controller"))
                PathSelectors. Any () represents all paths
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                // Set the document title (API name)
                .title("Swagger2 interface Document")
                // Document description
                .description("Interface Description")
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
                // Terms of Service URL
                .termsOfServiceUrl("https://swagger.io/")
                / / version number
                .version("1.0") .build(); }}Copy the code

If interceptors are used:

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    /** * interceptor */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                    throws Exception {

				// Your business logic...
                return true;

            }
        }).addPathPatterns("/ * *").excludePathPatterns("/login"."/register"."/login/doLogin"."/user/register"."/mystatic/**"."/druid/**"."/swagger-resources/**"."/webjars/**"."/v2/**"."/swagger-ui.html/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/"); }}Copy the code

If Spring Security is used:

@Override
    public void configure(WebSecurity web) throws Exception {
        //allow Swagger URL to be accessed without authentication
        web.ignoring().antMatchers("/v2/api-docs".//swagger api json
                "/swagger-resources/configuration/ui".// The action used to get support
                "/swagger-resources".// The URI used to get api-docs
                "/swagger-resources/configuration/security".// Security options
                "/swagger-ui.html");
    }
Copy the code

Then add the following annotations to the controller you want to access, for example (@API and @apiOperation annotations are used here) :

@RestController
@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
@Api(tags = "Login interface")
@RequestMapping("/login")
public class LoginController {


    @ApiOperation(value = "Login")
    @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
    public CommonResult doLogin(@RequestBody User user, HttpSession session) {

        if (("admin".equals(user.getUserName()) && "root".equals(user.getPassword()))) {

            session.setAttribute("user", user);
            return new CommonResult(ResultConstant.SUCCCSS_CODE, ResultConstant.SUCCESS_MSG);
        }
        return new CommonResult(ResultConstant.LOGIN_FAIL_CODE, ResultConstant.FAIL_MSG);

    }

    @ApiOperation(value = "Log out")
    @RequestMapping(value = "/doLogOut",method = RequestMethod.POST)
    public CommonResult doLogOut(HttpSession session) {

        session.removeAttribute("user");
        return newCommonResult(ResultConstant.SUCCCSS_CODE, ResultConstant.SUCCESS_MSG); }}Copy the code

Finally, the entity class adds annotations (@APIModel and @APIModelProperty) :

@ApiModel
public class User implements Serializable {

    /** * serialVersionUID */
    private static final long serialVersionUID = 1L;

	@ApiModelProperty(value = "Username", name = "userName")
	private String userName;

	@ApiModelProperty(value = "Password", name = "password")
	private String password;

	public String getUserName(a) {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword(a) {
		return password;
	}

	public void setPassword(String password) {
		this.password = password; }}Copy the code

Visit http://localhost:ip:port/ project path/swagger – UI. HTML:

Through this interface, you can also test the interface, greatly facilitating our development docking work, from now on to say goodbye to the maintenance of complex documents!

User-defined parameter configurations

The new version of the code generator adds the common parameter configuration interface, where you can select the connection pool type (currently support Druid and HikariCP) and whether to enable Swagger, as follows:

More parameters will be added!

Postgresql is also easy to use, just change the database type to PostgresQL:

Code generated in postgresQL mode may have problems because it has not been tested yet…

conclusion

With the technology, let’s look at the life, due to the influence of the outbreak, the impact of the domestic economy has been greatly, everywhere about layoffs, and other negative information, can’t find a job you don’t have to feel panic, there will be a rainbow after the storm, we need to do is to continuously improve their technical level, read more, learn more, become the core staff, In this way, to achieve a secure victory, sit huai not disorderly.

I hope foreign countries can control the development of the epidemic as soon as possible and defeat this cunning virus. It is really heart-wrenching to wake up every morning and see the growing numbers.

Finally, I hope that everyone should put health in the first place at any time. After all, the body is the capital of the revolution. Without health, everything will become meaningless.

Thanks for watching, see you next time!

The attached:

Generator download link:www.zrxlh.top:8088/coreCode/

Source code address:Gitee.com/zrxjava/cod…