1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/284520459-RichServlet

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
В этом репозитории не указан файл с открытой лицензией (LICENSE). При использовании обратитесь к конкретному описанию проекта и его зависимостям в коде.
Клонировать/Скачать
Внести вклад в разработку кода
Синхронизировать код
Отмена
Подсказка: Поскольку Git не поддерживает пустые директории, создание директории приведёт к созданию пустого файла .keep.
Loading...
README.md

RichServlet

Благодаря мощной NIO-инфраструктуре Netty, RichServlet позволяет создать легковесный и высокопроизводительный HTTP и HTTP2 restful сервер. При этом реализуется стандартный сервлетный протокол, который может работать со стандартными контейнерами сервлетов. Также поддерживается возможность создания плагинов, что делает разработку с использованием RichServlet простой и удобной, подобно Jetty.

Особенности RichServlet

  1. Может использоваться как отдельный HTTP и HTTP2 контейнер, реализуя стандартные функции HTTP restful и аналогичные Spring MVC аннотации.
  2. Реализует стандартный сервлетный протокол и может быть интегрирован в стандартные контейнеры сервлетов, аналогично настройке web.xml в веб-проектах. Это обеспечивает простоту и высокую производительность.
  3. Использует механизм изоляции классов Java ClassLoader.

Пример кода для RichServlet HTTP-сервера

  1. Пример restful:
@Controller
public class Controller1 {

    @RequestMapping(value = "/contract/new", method = RequestMethodEnums.POST)
    public
    @ResponseBody
    HttpResult<Boolean> createNewContract(
            @RequestParam("tenantId") Long tenantId,
            @RequestParam("baseId") String baseId,
            @RequestParam("resourceType") Integer resourceType,
            @Requestparam("specs") String specs
    ) {
        return new HttpResult<Boolean>();
    }

    // Другие методы опущены для краткости
}
  1. Запуск HTTP-сервера:
/**
 * 
 */
package com.apache.rich.servlet.http.server;

import com.apache.rich.servlet.http.server.RichServletHttpServer;
import com.apache.rich.servlet.http.server.RichServletHttpServerProvider;

import com.apache.rich.servlet.core.server.helper.RichServletServerOptions;
import com.apache.rich.servlet.core.server.monitor.RichServletServerMonitor;

/**
 * @author wanghailing
 *
 */
public class SimpleRichServletHttpServer {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
А здесь код обрывается. **Пример кода RichServletHttpServer**

RichServletHttpServer richServletHttpServer = RichServletHttpServerProvider.getInstance().service();  
// Отключаем внутренний контроллер корневого пути  
richServletHttpServer.disableInternalController();  
// Отключаем монитор статистики  
RichServletServerMonitor.disable();

// 2. Выбираем параметры HTTP. Это необязательно  
richServletHttpServer  
    .option(RichServletServerOptions.IO_THREADS, Runtime.getRuntime().availableProcessors())  
    .option(RichServletServerOptions.WORKER_THREADS, 128)  
    .option(RichServletServerOptions.TCP_BACKLOG, 1024)  
    .option(RichServletServerOptions.TCP_NODELAY, true)  
    .option(RichServletServerOptions.TCP_TIMEOUT, 10000L)  
    // .option(RichServletServerOptions.TCP_HOST,"127.0.0.1")  
    .option(RichServletServerOptions.TCP_PORT,8080)  
    .option(RichServletServerOptions.MAX_CONNETIONS, 4096);

richServletHttpServer.scanHttpController("test.apache.rich.servlet.http.server.rest");

// 3. Запускаем HTTP-сервер  
if (!richServletHttpServer.start()){  
    System.err.println("HttpServer run failed");  
}  
try {  
    richServletHttpServer.join();  
    richServletHttpServer.shutdown();  
} catch (InterruptedException ignored) {  
}

**Пример кода класса TestServlet**  

import java.io.IOException;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
public class TestServlet extends HttpServlet{  
  
/**  
 *  
 */  
private static final long serialVersionUID = 9177182925005765109L;  
  
@Override  
protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
        throws ServletException, IOException {  
    System.out.println("okdoGet:"+req.getParameterNames());  
}  
  
@Override  
protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
        throws ServletException, IOException {  
    System.out.println("doPost");  
    super.doPost(req, resp);  
}  
}

**Конфигурация web.xml**  
<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
<!-- 登录请求 -->  
<servlet>  
    <servlet-name>testServlet</servlet-name>  
    <servlet-class>com.apache.rich.servlet.server.servlet.TestServlet</servlet-class>  
</servlet>  
<servlet-mapping>  
    <servlet-name>testServlet</servlet-name>  
    <url-pattern>/testServlet</url-pattern>  
</servlet-mapping>
</web-app>

**Свойства server.properties**  
WORKER_THREADS=10  
TCP_BACKLOG=1024  
TCP_PORT=8080  
MAX_CONNETIONS=1024  
SUPPORT_TYPE=httpservlet  
WEBAPP_NAME=/

**Запуск httpservlet-сервера**  
./RichServletServer.sh

**Код httpservlet-server**  
/**  
*  
*/  
package com.apache.rich.servlet.server;  
  
import java.io.BufferedInputStream;  
import java.io.FileInputStream;  
import java.io.InputStream;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import java.util.Properties;  
  
import javax.servlet.Filter;  
import javax.servlet.http.HttpServlet;  
  
import com.alibaba.fastjson.JSONObject;  
  
import com.apache.rich.servlet.server.servlet.TestServlet;  
import com.apache.rich.servlet.server.classloader.RichServletClassloader;  
import com.apache.rich.servlet.http.servlet.server.RichServletHttpServletServerProvider;  
import com.apache.rich.servlet.http.servlet.realize.RichServletHttpServlet;  
import com.apache.rich.servlet.http.servlet.realize.configuration.RichServletHttpFilterConfiguration;  
import com.apache.rich.servlet.http.servlet.realize.configuration.RichServletHttpServletConfiguration;  
import com.apache.rich.servlet.http.servlet.realize.configuration.RichServletHttpWebappConfiguration;  
import com.apache.rich.servlet.http2.server.RichServletHttp2Server;  
import com.apache.rich.servlet.http2.server.RichServletHttp2ServerProvider; **Автор: wanghailing**

import com.apache.rich.servlet.core.server.helper.RichServletServerOptions; import com.apache.rich.servlet.core.server.monitor.RichServletServerMonitor; import com.apache.rich.servlet.http.server.RichServletHttpServer; import com.apache.rich.servlet.http.server.RichServletHttpServerProvider; import com.apache.rich.servlet.server.enums.RichServletServerEnums; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.apache.rich.servlet.common.enums.ErrorCodeEnums; import com.apache.rich.servlet.common.exception.HServerException;

/**

  • @author wanghailing */ public class NBRichServletServer { private static final Logger log = LoggerFactory.getLogger(NBRichServletServer.class);

    private RichServletServerBean richServletServerBean;

    public NBRichServletServer() { try { richServletServerBean = loadClassFromXml(); } catch (Exception e) { log.error("loadClassFromXml error ", e); } }

    /**

    • Инициализация */ public void init() { try { log.info("----NBRichServletServer init start-----"); doInit(); log.info("----NBRichServletServer init end-----"); } catch (HServerException e) { log.error("----NBRichServletServer init error-----", e); } }

    /**

    • Система параметров инициализации */ private void doInit() throws HServerException { if (richServletServerBean != null) { validateParameters(richServletServerBean); if (RichServletServerEnums.http.toString().equals(richServletServerBean.getSupportType())) { // Чистый httpserver сервер startHttpServer(); } else if (RichServletServerEnums.http2.toString().equals(richServletServerBean.getSupportType())) { // Чистый http2 server сервер startHttp2Server(); } else if (RichServletServerEnums.httpservlet.toString().equals(richServletServerBean.getSupportType())) { // Чистый httpservlet server сервер startHttpServletServer(); } } else { throw new HServerException(ErrorCodeEnums.PARAMETER_ERROR.getErrorCode(), "richServletServerBean is null, parameters can not be null "); } }

    // Запуск httpserver сервера private void startHttpServer() throws HServerException { RichServletHttpServer richServletHttpServer = RichServletHttpServerProvider.getInstance().service(); // Отключить внутренний контроллер корневого пути richServletHttpServer.disableInternalController(); // Отключить монитор статистики RichServletServerMonitor.disable(); // 2. Выбрать параметры http. Это не нужно richServletHttpServer .option(RichServletServerOptions.IO_THREADS, Runtime.getRuntime().availableProcessors()) .option(RichServletServerOptions.WORKER_THREADS, richServletServerBean.getWorkThreads()) .option(RichServletServerOptions.TCP_BACKLOG, richServletServerBean.getTcpBacklogs()) //.option(RichServletServerOptions.TCP_HOST,richServletServerBean.getServerHost()) .option(RichServletServerOptions.TCP_PORT, richServletServerBean.getServerPort()) .option(RichServletServerOptions.MAX_CONNETIONS, richServletServerBean.getMaxConnections()); richServletHttpServer.scanHttpController(richServletServerBean.getScanControllerPatch()); // 3. Запустить http сервер if (!richServletHttpServer.start()) { //System.err.println("HttpServer run failed"); log.error("startHttpServer error"); } try { // Присоединиться и подождать здесь richServletHttpServer.join(); richServletHttpServer.shutdown(); } catch (InterruptedException ignored) { log.error("startHttpServer error", ignored); } }

    /**

    • Запуск http2server сервера
    • @throws HServerException */ private void startHttp2Server() throws HServerException { RichServletHttp2Server } }

// Отключаем внутренний контроллер корневого пути
**richServletHttp2Server.disableInternalController();**

// Отключаем монитор статистики
**RichServletServerMonitor.disable();**

**richServletHttp2Server**
**.option(RichServletServerOptions.IO_THREADS, Runtime.getRuntime().availableProcessors())**
**.option(RichServletServerOptions.WORKER_THREADS, richServletServerBean.getWorkThreads())**
**.option(RichServletServerOptions.TCP_BACKLOG, richServletServerBean.getTcpBacklogs())**
//**.option(RichServletServerOptions.TCP_HOST,richServletServerBean.getServerHost())**
**.option(RichServletServerOptions.TCP_PORT,richServletServerBean.getServerPort())**
**.option(RichServletServerOptions.MAX_CONNETIONS, richServletServerBean.getMaxConnections());**

**richServletHttp2Server.scanHttpController(richServletServerBean.getScanControllerPatch());**

// 3. Запускаем HTTP-сервер
**if (!richServletHttp2Server.start()){**
    //System.err.println("HttpServer run failed");
    **log.error("startHttp2Server error");**
}

**try {**
    // Присоединяемся и ждём здесь
    **richServletHttp2Server.join();**
    **richServletHttp2Server.shutdown();**
} **catch (InterruptedException ignored) {**
    **log.error("startHttp2Server error",ignored);**
}

*/***
* Запуск HttpServlet-сервера
* @throws HServerException
***/
private void startHttpServletServer() throws HServerException{**

    RichServletHttpWebappConfiguration configuration = new RichServletHttpWebappConfiguration();
    configuration.addServletConfigurations(new RichServletHttpServletConfiguration(TestServlet.class,"/testServlet"));

    if(richServletServerBean.getHttpServletBeans()!=null&&richServletServerBean.getHttpServletBeans().size()>0){
        for(HttpServletBean httpServletBean:richServletServerBean.getHttpServletBeans()){
            if(httpServletBean.getHttpServlet()!=null&&httpServletBean.getServletpath()!=null){
                configuration.addServletConfigurations(new RichServletHttpServletConfiguration(httpServletBean.getHttpServlet(),httpServletBean.getServletpath()));
            }               
        }
    }
    if(richServletServerBean.getHttpFilterBeans()!=null&&richServletServerBean.getHttpFilterBeans().size()>0){
        for(HttpFilterBean httpFilterBean:richServletServerBean.getHttpFilterBeans() ){
            if(httpFilterBean.getFilter()!=null&&httpFilterBean.getFilterpath()!=null){
                configuration.addFilterConfigurations(new RichServletHttpFilterConfiguration(httpFilterBean.getFilter(),httpFilterBean.getFilterpath()));
            }
        }
    }   
    RichServletHttpServlet servletHttpServlet=new RichServletHttpServlet(configuration,richServletServerBean.getWebpatch());
    com.apache.rich.servlet.http.servlet.server.RichServletHttpServletServer httpServletServer=RichServletHttpServletServerProvider.getInstance().service(servletHttpServlet);
    //httpServletServer.disableInternalController();
        // Отключаем мониторинг статистики
    RichServletServerMonitor.disable();

        // 2. Выбираем параметры HTTP. Это необязательно
    httpServletServer.option(RichServletServerOptions.IO_THREADS, Runtime.getRuntime().availableProcessors())
                .option(RichServletServerOptions.WORKER_THREADS, richServletServerBean.getWorkThreads())
                .option(RichServletServerOptions.TCP_BACKLOG, richServletServerBean.getTcpBacklogs())
                //.option(RichServletServerOptions.TCP_HOST,richServletServerBean.getServerHost())
                .option(RichServletServerOptions.TCP_PORT,richServletServerBean.getServerPort())
                .option(RichServletServerOptions.MAX_CONNETIONS, richServletServerBean.getMaxConnections());
        // 3. Запускаем HTTP-сервер
                if

В запросе присутствуют фрагменты кода на языке Java. ```
richServletServerBean.setTcpBacklogs(Integer.parseInt(pps.getProperty("TCP_BACKLOG")));
richServletServerBean.setSupportType(pps.getProperty("SUPPORT_TYPE"));
richServletServerBean.setWebpatch(pps.getProperty("WEBAPP_NAME"));
}

public static void main(String[] args) throws Exception {
NBRichServletServer nbRichServletServer=new NBRichServletServer();
nbRichServletServer.doInit();
}

Комментарии ( 0 )

Вы можете оставить комментарий после Вход в систему

Введение

Описание недоступно Развернуть Свернуть
Отмена

Обновления

Пока нет обновлений

Участники

все

Недавние действия

Загрузить больше
Больше нет результатов для загрузки
1
https://api.gitlife.ru/oschina-mirror/284520459-RichServlet.git
git@api.gitlife.ru:oschina-mirror/284520459-RichServlet.git
oschina-mirror
284520459-RichServlet
284520459-RichServlet
master