Spring Boot + Gradle + Websocket build push service

Source: Internet
Author: User
Tags error handling exception handling getmessage mongodb valid mongodb support jcenter
Spring Boot + Gradle + Websocket build push service Introduction

Spring boot after a long period of development, has gradually become my first choice of microservices development, this article to build a push micro-service as an example, demonstrates how to use spring boot for efficient micro-service development. related technologies used gradle Spring boot and its starters WebSocket MongoDB APNs Docker gradle

As a rising star, both support the original MAVEN warehouse, but also has a concise syntax, not only can do dependency management, but also a convenient building tools. Can be said to be the perfect choice.

Build.gradle

Buildscript {
    repositories {
        jcenter ()
    }

    dependencies {
        classpath ("Org.springframework.boot: Spring-boot-gradle-plugin:1.3.3.release ")
    }
}

Apply plugin: ' java '
apply plugin: ' Spring-boot '

repositories {
    jcenter ()
}

dependencies {
    compile ("Org.springframework.boot: Spring-boot-starter-web ")
    testcompile (" Org.springframework.boot:spring-boot-starter-test ")
}
Sprnig Boot Starter

It's easier to use spring boot, as long as you reference the required starter. Spring-boot-starter-web Web project is required, automatically contains Tomcat and SPRING-WEBMVC Spring-boot-starter-data-mongodb we use the MongoDB database, Directly using the MongoDB support of spring data, declarative database access, the efficiency greatly improved. Spring-boot-starter-websocket WebSocket supports spring-boot-starter-security Spring Security support, universal selection Spring-boot-starter-actuator production features support, this is also a tool, DevOps preferred. Dev Tools

The excellent framework is first of all developer-friendly, spring boot does a good job in this, hot swapping feature makes development without the need to start the service frequently.
I am using IntelliJ idea, a little more trouble, idea of the automatic compilation function in the program run or debugging does not work, can only be used CTRL+F9
Hot swapping is configured in idea as follows:
Build.gradle

Buildscript {
    repositories {
        jcenter ()
    }
    dependencies {
        classpath "Org.springframework.boot: Spring-boot-gradle-plugin:1.3.3.release "
        classpath" Org.springframework:springloaded:1.2.6.release "
    }
}
...
Apply plugin: ' idea ' idea

{
    module {
        inheritoutputdirs = false
        OutputDir = File ("$buildDir/classes /main/")
    }
}

This allows the manual ctrl+f9 to take effect every time the code is modified. However, it is necessary to restart the service if it involves a change in the method interface. application Configuration

Spring boot supports the properties and Yaml two ways, I recommend the use of Yaml mode, indentation easier to read.
Application.yaml

Spring:
  data:
    MongoDB:
      uri:mongodb://localhost:27017/onepush
pushserver:
  env:dev #开发或正式
server:
  port:8080
...

Referencing custom configurations is also particularly easy, using @configurationproperties directly.
such as: Pushserverconfig.java

@ConfigurationProperties (prefix= "Pushserver") public
class Pushserverconfig {
    private String env;
    Get,set methods ...
}

Configuration items with the same name under Pushserver are automatically referenced. Validation

Spring provides validator support and provides helper classes to help developers implement custom check logic.
Implementation steps:
-Implement a custom check class
Pushvalidator.java

@Component public
class Pushvalidator implements validator{
    @Override public
    Boolean supports (CLASS<? > Clazz) {
        return UserDevice.class.equals (clazz) | | PushRequest.class.equals (Clazz);
    }

    @Override public
    void Validate (Object obj, Errors e) {
        validationutils.rejectifemptyorwhitespace (E, "AppId", " Field.required ", New string[]{" AppId "});
        ...
    }
}
Enable in controller, add validator to binder, use @valid ... Bindingresult Bindresult can
Pushcontroller.java
    @InitBinder public
    void Initbinder (DataBinder binder) {
        binder.setvalidator (validator);
    }

    @RequestMapping (value= "/register", method= requestmethod.post)
    map<string,string> Register (@Valid @ Requestbody userdevice Userdevice, Bindingresult bindresult) {
        if (bindresult.haserrors ()) {
            throw new Pushparameterexception (GetErrorString (Bindresult));
        }
        ...
Exception Handling

Define two types of application exceptions:
pushparameterexception– Request parameter Error class exception
pushserviceexception– Service Handling Class exception
The main function of distinguishing between these two types of exceptions is to make it possible for clients to use different error handling mechanisms for different exceptions.
If the parameter error class exception reminds the user to modify the parameter re-request, the retry mechanism can be used for the service handling class exception.

For these two kinds of exceptions, a uniform application exception handler is implemented.
Pushexceptionadvice.java

@ControllerAdvice public class Pushexceptionadvice extends responseentityexceptionhandler{@ExceptionHandler ( Pushparameterexception.class) public responseentity<errorresponse> handleparameterexception (
        Pushparameterexception e) {errorresponse er = null;
        if (Pushserverconfig.isprod ()) {er = new errorresponse (E.getcode (), e.getmessage (), NULL);
        } else {er = new errorresponse (E.getcode (), E.getmessage (), E.getcause ());
    } return new responseentity<errorresponse> (er, httpstatus.bad_request); } @ExceptionHandler (Pushserviceexception.class) public responseentity<errorresponse> handleserviceexception (Pushserviceexception e)
        {Errorresponse er = null;
        if (Pushserverconfig.isprod ()) {er = new errorresponse (E.getcode (), e.getmessage (), NULL);
        } else {er = new errorresponse (E.getcode (), E.getmessage (), E.getcause ()); } return new ResponsEentity<errorresponse> (er, httpstatus.service_unavailable); }

}
other

This project has been uploaded to GitHub, welcome to download.

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.