Spring Boot+Grade+Websocket構築プッシュサービス

5182 ワード

紹介する
Spring Bootは長期的な発展を経て、マイクロサービス開発の第一選択となりました.本稿では、プッシュマイクロサービスを構築することを例にして、spring bootを使って効率的なマイクロサービス開発を行う方法を実証します.
使用する技術
  • gradle
  • spring boot及びstarters
  • websocket
  • mongodb
  • apps
  • docker
  • Grade
    後進のショーとして、既存のMaven倉庫をサポートしながら、簡潔な文法を持っています.管理に頼るだけでなく、便利な構築ツールです.不二の選択とも言える.
    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")
    }
    
    Spring Boot
    スターター
    Spring bootを使うのは簡単です.必要なstarterを引用すればいいです.
  • spring-boot-starter-web web webプロジェクトは必ず選んで、自動的にtomcatとspring-webmvc
  • を含みました.
  • spring-boot-starter-data-mongodb私達はmongodbデータベースを使って、直接spring dataのmongodbを使って支持して、声明式のデータベースの訪問、効率は大いに向上します.
  • spring-boot-starter-websocket websocketは
  • をサポートします.
  • spring-boot-starter-security spring securityサポート、汎用選択
  • spring-boot-starter-actuat生産特性は支持して、これも利器で、devopsは第一選択です.
  • Dev tools
    優れた枠組みはまず開発者に友好的で、spring bootはこの面でよく作られています.Hot swapping特性は開発時に頻繁にサービスを開始しなくてもいいです.本人が使っているのはIntelliJ IDEAです.少々面倒ですが、IDEAの自動コンパイル機能はプログラム運転やデバッグ時には機能しません.Ctrl+F 9 Hot swappingでIDEAでの配置は以下の通りです.
    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/")
        }
    }
    
    このように、コードを修正するたびに手動Ctrl+F 9が有効になります.しかし、方法インターフェースの変更などに関しては、サービスを再開する必要があります.
    設定を適用
    spring bootはpropertiesとyamlの両方をサポートしています.本人はyaml方式を使うことを勧めています.縮め方が読みやすいです.appication.yaml
    spring:
      data:
        mongodb:
          uri: mongodb://localhost:27017/onepush
    pushserver:
      env: DEV #     
    server:
      port: 8080
    ...
    
    引用カスタム構成も簡単です.直接@CofigrationProptiesを使えばいいです.Push Server Config.java
    @ConfigurationProperties(prefix="pushserver")
    public class PushServerConfig {
        private String env;
        get,set methods...
    }
    
    pusserverの下の同じ名前の配置項目を自動的に参照します.
    validation
    SpringはValidatorのサポートを提供しており、いくつかの補助類が開発者にカスタム検証ロジックを実現するように助けてくれます.実装ステップ:
  • カスタムチェッククラスPush Validator.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"});
            ...
        }
    }
    
  • はcontrollerで有効にして、validartをbinderに追加して、@Validを使って、BindingResult bindResultを使って、Push Controller.java
  • を使うことができます.
        @InitBinder
        public void initBinder(DataBinder binder) {
            binder.setValidator(validator);
        }
    
        @RequestMapping(value="/register", method= RequestMethod.POST)
        Map register(@Valid @RequestBody UserDevice userDevice, BindingResult bindResult) {
            if (bindResult.hasErrors()) {
                throw new PushParameterException(getErrorString(bindResult));
            }
            ...
    
    
    異常処理
    2種類のアプリケーションの異常を定義します.Push Parameter Exception-要求パラメータのエラー種類の異常Push ServiceException--サービス処理類の異常区分の2つの異常の主要な役割は、クライアントが異なる異常に対して異なるエラー処理メカニズムを採用する可能性があることです.パラメータエラークラスに異常がある場合は、パラメータ再要求をユーザーに修正してもらうようにします.サービス処理クラスの異常に対しては、再試行機構を採用することができます.
    これらの異常に対して、アプリケーション異常処理の統一を実現します.Push Exception Advice.java
    @ControllerAdvice
    public class PushExceptionAdvice extends ResponseEntityExceptionHandler{
        @ExceptionHandler(PushParameterException.class)
        public ResponseEntity 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(er, HttpStatus.BAD_REQUEST);
        }
    
        @ExceptionHandler(PushServiceException.class)
        public ResponseEntity 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(er, HttpStatus.SERVICE_UNAVAILABLE);
        }
    }
    
    その他
    本プロジェクトはすでにgithubにアップロードされました.ダウンロードを歓迎します.