storm-server使用指南

@author stormma
@date 2017/09/15


生命不息,奮鬥不止


storm-server使用指南

storm-server介紹

storm-server, 以jetty爲servlet容器的一個java web框架, 主要用於爲前端提供api服務, 具有快速開發的優勢。storm-server之後會提供一些操作mysql, redis的工具, storm-server旨在快速開發一些小型的web應用, 以及用於日常學習。storm-server github地址: https://github.com/stormmaybin/storm-server.git, 歡迎各位star和參與開發,storm-server期待你的參與與建議。

小試牛刀
引入storm-server依賴(最新版本1.0,後期會跟進升級和維護)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.stormmaybin</groupId>
    <artifactId>storm-server-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <storm-server.version>1.0</storm-server.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>me.stormma</groupId>
            <artifactId>storm-server</artifactId>
            <version>${storm-server.version}</version>
        </dependency>
    </dependencies>
</project>
添加storm.properties配置文件
storm.server.port=8057 # 端口默認爲8057
storm.server.module=storm_server_test #模塊名
storm.ansi.output.enabled=true # 不同級別日誌顯示顏色不同

storm-server默認去classpath下讀取storm.properties配置文件, 當然, 你也可以指定配置文件的路徑和名字, 如果你選擇這麼做了,那麼你要在運行啓動類時候傳入配置文件的完整路徑, 例如: 假如我的配置文件名字叫application.properties, 放在resources/config/,那麼你需要在運行啓動類(下面會說到)的時候傳入參數’resources/config/application.properties’。

添加logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="logback/base.xml" />
</configuration>

storm-server使用logback日誌系統,storm-server已經提供了base.xml, 你只需要新建logback.xml,添加base.xml即可,當然你也可以加入自己的配置。

啓動storm-server
package com.github.stormmaybin.controller;

import me.stormma.StormApplication;
import me.stormma.annotation.Application;
import me.stormma.annotation.ComponentScan;

/**
 * @description 啓動類
 * @author stormma 
 * @date 2017/09/15
 */
@ComponentScan
@Application(StormServerTestApplication.class)
public class StormServerTestApplication {
    public static void main(String[] args) {
        StormApplication.run(args);
    }
}
新建service
package com.github.stormmaybin.controller.service.impl;

import com.github.stormmaybin.controller.model.User;
import com.github.stormmaybin.controller.service.ITestService;
import me.stormma.ioc.annotation.Service;

/**
 * @description
 * @author stormma
 * @date 2017/09/15
 */
@Service
public class TestService implements ITestService {

    @Override
    public User getUserById(int uid) {
        //模擬dao層操作
        User user = new User();
        user.setUsername("stormma");
        user.setPassword("stormma");
        return user;
    }
}

@Service註解聲明此類是一個service, 這與spring mvc/boot保持一致

新建controller
package com.github.stormmaybin.controller.controller;

import com.github.stormmaybin.controller.model.User;
import com.github.stormmaybin.controller.service.ITestService;
import me.stormma.core.http.annotation.Api;
import me.stormma.core.http.annotation.JsonParam;
import me.stormma.core.http.annotation.RequestParam;
import me.stormma.core.http.enums.RequestMethod;
import me.stormma.core.http.model.HttpContext;
import me.stormma.core.http.response.Response;
import me.stormma.core.http.response.builder.ResponseBuilder;
import me.stormma.ioc.annotation.AutoWired;
import me.stormma.ioc.annotation.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author stormma
 * @date 2017/09/15
 */
@Controller("/api")
public class TestController {

    @AutoWired
    private ITestService testService;

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    /**
     * 測試無參數情況的數據響應
     * @return
     */
    @Api(url = "/hello", method = RequestMethod.GET)
    public Response<String> hello() {
        return ResponseBuilder.success("hello storm-server");
    }

    /**
     * 測試綁定HttpContext
     * @param context
     * @return
     */
    @Api(url = "/date", method = RequestMethod.GET)
    public Response<Date> getCurrentDate(HttpContext context) {
        logger.info("訪問路徑:{}", context.requestPath);
        return ResponseBuilder.success(new Date());
    }

    @Api(url = "/array/int", method = RequestMethod.GET)
    public Response<String> testIntArray(@RequestParam(name = "id") int[] ids) {
        for (int id: ids) {
            logger.info("{}", id);
        }
        return ResponseBuilder.success();
    }

    @Api(url = "/array/Integer", method = RequestMethod.GET)
    public Response<String> testIntegerArray(@RequestParam(name = "id") Integer[] ids) {
        for (Integer id: ids) {
            logger.info("{}", id);
        }
        return ResponseBuilder.success();
    }

    @Api(url = "array/float", method = RequestMethod.GET)
    public Response<String> testFloatArray(@RequestParam(name = "id") float[] ids) {
        for (float id: ids) {
            logger.info("{}", id);
        }
        return ResponseBuilder.success();
    }

    @Api(url = "array/Float", method = RequestMethod.GET)
    public Response<String> testFloatArray(@RequestParam(name = "id") Float[] ids) {
        for (Float id: ids) {
            logger.info("{}", id);
        }
        return ResponseBuilder.success();
    }

    @Api(url = "array/Double", method = RequestMethod.GET)
    public Response<String> testDoubleArray(@RequestParam(name = "id") Double[] ids) {
        for (Double id: ids) {
            logger.info("{}", id);
        }
        return ResponseBuilder.success();
    }

    @Api(url = "array/double", method = RequestMethod.GET)
    public Response<String> testDoubleArray(@RequestParam(name = "id") double[] ids) {
        for (double id: ids) {
            logger.info("{}", id);
        }
        return ResponseBuilder.success();
    }

    @Api(url = "array/boolean", method = RequestMethod.GET)
    public Response<String> testBooleanArray(@RequestParam(name = "id") boolean[] ids) {
        for (boolean id: ids) {
            logger.info("{}", id);
        }
        return ResponseBuilder.success();
    }

    @Api(url = "array/Boolean", method = RequestMethod.GET)
    public Response<String> testBooleanArray(@RequestParam(name = "id") Boolean[] ids) {
        for (Boolean id: ids) {
            logger.info("{}", id);
        }
        return ResponseBuilder.success();
    }

    /**
     * 測試query string參數類型,和json參數類型結合的綁定
     * @param id
     * @param user
     * @return
     */
    @Api(url = "/get/user", method = RequestMethod.POST)
    public Response<User> test(@RequestParam(name = "id") int id, @JsonParam User user) {
        System.out.println(user);
        User result = testService.getUserById(id);
        logger.info("json 參數: {}", user);
        logger.info("{}", result);
        return ResponseBuilder.success(result);
    }
}

storm-server建議響應數據統一化,controller method返回值都是Response 類型,Response是storm-server提供的一個響應數據封裝類。

public class Response<T> {
    /**
     * error code :錯誤是1、成功是0
     */
    private Integer code;

    /**
     * 本次請求的status
     */
    private Integer status;

    /**
     * 要返回的數據
     */
    private T data;

    /**
     * 本次請求的說明信息
     */
    private String msg;

controller的用法和spring boot/mvc差別不大,storm-server提供了參數自動綁定,內部提供了String2Boolean, 默認的String2Date,還有String2Number三種轉換器, 當然,如果這三種轉換器不夠滿足你項目的需求,你也可以自定義一個converter, 實現Converter

public class DefaultStringToDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) throws StormServerException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(source);
        } catch (ParseException e) {
            throw new StormServerException("string convert to date failed, because param is not valid.");
        }
        return date;
    }
}

同樣,storm-server提供了json參數自動綁定到對象上,@JsonParam註解可以幫你完成這個冗餘的操作。

啓動storm-server

使用maven打成可執行jar
  • 添加打包插件
<!--打包可執行jar-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.github.stormmaybin.controller.StormServerTestApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <!--引用第三方jar-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

你要做的就是修改 MainClass 爲你的啓動類, 也就是調用 StormApplication.run(args) 的那個類。

mvn clean package

打包結束之後會出現一個xxx.jar,然後執行java -jar xxx.jar即可運行。

結束語

storm-server從開始開發到1.0版本的發佈歷經了1個月,這一個月其中的兩週因爲一些事情一行代碼都沒寫,所以今天匆匆茫茫發佈了1.0版本之後,甚是心虛,我深知storm-server現在還遠遠不夠完善,但是作爲學習資料足夠了。我相信,storm-server後期的升級與維護,離不開你的支持、參與和建議,如果你對storm-server感興趣,歡迎參與討論,本人企鵝號: 1325338799, email: [email protected]


本文來自我的個人博客轉載請註明出處!

storm-server對您有幫助? 求讚賞鼓勵支持。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章