jersey+jetty实现restful接口,嵌入式,无需tomcat部署

build.gradle:

import org.apache.tools.ant.filters.FixCrLfFilter;
import org.apache.tools.ant.filters.ReplaceTokens;

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'

project.group = 'com.soft'
project.archivesBaseName = 'jersey-jetty'
project.version = ''

tasks.withType(JavaCompile) { 
    sourceCompatibility = "1.8"
    targetCompatibility = "1.8"
    options.encoding="UTF-8"
}

javadoc { options.encoding = "UTF-8" }

repositories {
        mavenLocal()
        maven{ url "http://maven.aliyun.com/nexus/content/groups/public" }
}

dependencies {
        
        compile 'cn.hutool:hutool-all:5.3.5'
        
        compile 'org.glassfish.jersey.containers:jersey-container-jetty-http:2.34'
        compile 'org.glassfish.jersey.containers:jersey-container-servlet-core:2.34'
        compile 'org.glassfish.jersey.inject:jersey-hk2:2.34'
        compile 'org.glassfish.jersey.media:jersey-media-json-jackson:2.34'
        compile 'org.eclipse.jetty:jetty-server:9.4.31.v20200723'
        compile 'org.eclipse.jetty:jetty-servlet:9.4.31.v20200723'
        compile 'org.eclipse.jetty:jetty-util:9.4.31.v20200723'
        
        compile 'org.slf4j:slf4j-api:2.0.0-alpha1'
        runtime 'org.slf4j:jcl-over-slf4j:2.0.0-alpha1'
        runtime 'ch.qos.logback:logback-classic:1.3.0-alpha5'
      
        compile group: 'org.mybatis', name: 'mybatis', version: '3.5.4'
        compile group: 'com.zaxxer', name: 'HikariCP', version: '3.4.5'
        runtime 'com.oracle:ojdbc6:11.2.0.3'
        
        compileOnly 'org.projectlombok:lombok:1.18.12'
        annotationProcessor 'org.projectlombok:lombok:1.18.12'    
}

task libs(type: Copy) {
    from configurations.runtime
    into "$buildDir/libs"
}

task makeJar(type:org.gradle.api.tasks.bundling.Jar) {
    from('build/classes/java/main')
    exclude('*.properties', '*.xml','*.setting')
} 

processResources(){
    filter(ReplaceTokens,tokens: loadEnv());
    filter ReplaceTokens, tokens: [
        "version": version
    ]
    
    filter(FixCrLfFilter,
        eol: FixCrLfFilter.CrLf.newInstance('lf'),
        tab: FixCrLfFilter.AddAsisRemove.newInstance('asis'),
        tablength: 4,
        eof: FixCrLfFilter.AddAsisRemove.newInstance('remove'),
        fixlast: true)
}

task processShell(type: Copy) {
    description = " copy shell scripts to buildDir/shell"
    from 'src/main/sh'
    into "$buildDir/sh"
    filter(ReplaceTokens,tokens: loadEnv());
    filter(FixCrLfFilter,
        eol: FixCrLfFilter.CrLf.newInstance('lf'),
        tab: FixCrLfFilter.AddAsisRemove.newInstance('asis'),
        tablength: 4,
        eof: FixCrLfFilter.AddAsisRemove.newInstance('remove'),
        fixlast: true)
}

test {
    systemProperties 'property': 'value'
}

task deploy(type: Copy) {
    description = ' deploy all the binary and config files to destination(prefix) '
    def destFold=file("$prefix")
    into(destFold)
    from("$buildDir/libs"){
        into("lib")
    }
    from("$buildDir/sh"){
        into("sh")
    }
    from("$buildDir/resources/main"){
        into("conf")
    }
    
    doFirst{
        logger.lifecycle("deploy files to : $destFold")
    }
    doLast{
        logger.lifecycle("deploy success!")
    }
}

task preDeploy(){
    description = ' pre actions for task deploy'
    def logsdir=file("$prefix/log")
    if(!logsdir.exists()){
        logsdir.mkdir();
    }
    def libs=fileTree("$prefix/lib")
    libs.each {jar ->
        jar.delete()
    }
    def configs=fileTree("$prefix/conf")
    configs.each {conffile ->
        conffile.delete()
    }
}


libs.dependsOn(makeJar)
build.dependsOn(['libs','processShell','processResources'])

deploy.dependsOn preDeploy
deploy.dependsOn build

env/config.groovy:

prefix='/output'

environments {
    
    dev {
        sh{
            WORK_HOME='/home/xxx/newitf/jersey-jetty';
            PNAME='jersey-jetty';
            LANG='zh_CN.utf8';
            JAVA_HOME='/home/xxx/app/jdk/jdk8';
        }
    }
    
}

AppStart.java

package com.soft;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.soft.server.JettyServer;

public class AppStart {
	private static final Logger log = LoggerFactory.getLogger(AppStart.class);

	public static void main(String... args) {
		new AppStart().start();
	}

	private JettyServer server;

	public AppStart() {
		server = new JettyServer();
	}

	public void start() {
		try {
			server.start();
			server.join();
		} catch (Exception e) {
			log.error("", e);
		} finally {
			server.destroy();
		}
	}

}

JettyServer

package com.soft.server;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.InetAccessHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.soft.config.ServerConf;

import cn.hutool.core.util.StrUtil;

public class JettyServer {
	private static final Logger log = LoggerFactory.getLogger(JettyServer.class);

	private static final int port = ServerConf.VO.getPort();
	private static final String contextPath = ServerConf.VO.getContextPath();
	private static final String resourceBase = ServerConf.VO.getResourceBase();
	private static final int maxThreads = ServerConf.VO.getMaxThreads();
	private static final String ipWhiteList = ServerConf.VO.getIpWhiteList();

	private Server server;

	public JettyServer() {
	}

	public void start() throws Exception {
		server = new Server(createThreadPool());
		server.addConnector(createConnector());
		server.setHandler(createHandlers());
		server.setStopAtShutdown(true);
		server.start();
	}

	public void join() throws InterruptedException {
		server.join();
	}

	public void destroy() {
		server.destroy();
	}

	private ThreadPool createThreadPool() {
		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setName("embed-jetty-http");
		threadPool.setMinThreads(1);
		threadPool.setMaxThreads(maxThreads);
		return threadPool;
	}

	private ServerConnector createConnector() {
		ServerConnector connector = new ServerConnector(server);
		connector.setPort(port);
		log.info("App start at port: {}", port);
		return connector;
	}

	private HandlerCollection createHandlers() {
		ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
		// handler.setSessionHandler(new SessionHandler());
		handler.setContextPath(contextPath);
		handler.setResourceBase(resourceBase);
		ServletHolder holder = handler.addServlet(ServletContainer.class, "/*");
		holder.setInitOrder(1);

		holder.setInitParameter("jersey.config.server.provider.packages", "com.soft.controller");

		// InetAccessHandler ipHandler = getFireWallHandler();

		HandlerCollection handlerCollection = new HandlerCollection();
		handlerCollection.setHandlers(new Handler[] { handler });
		return handlerCollection;
	}

	private static InetAccessHandler getFireWallHandler() {
		InetAccessHandler ipHandler = new InetAccessHandler();
		if (StrUtil.isBlank(ipWhiteList)) {// 空,不配置,则不校验
			return ipHandler;
		}

		String[] ipList = ipWhiteList.split(",");
		for (String ip : ipList) {
			ipHandler.include(ip);
		}
		return ipHandler;
	}

}

UserController:

package com.soft.controller;

import java.util.Date;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.soft.po.User;
import com.soft.util.Result;

@Path("/abc")
public class UserController {
	private static final Logger log = LoggerFactory.getLogger(UserController.class);

	@GET
	@Path("/hello")
	@Produces(MediaType.TEXT_PLAIN)
	public String hi() {
		return "hello jersey";
	}

	@GET
	@Path("/{username}/{age}")
	@Produces(MediaType.APPLICATION_JSON)
	public Result findByKey(@PathParam("username") String username, @PathParam("age") int age) {
		log.info("接收到请求" + username);
		User user = new User();
		user.setUsername(username);
		user.setAge(age);
		user.setStatus(20);
		user.setModdate(new Date());
		return Result.ok(user);

	}
}

Result:

package com.soft.util;

import com.soft.exception.ErrorType;

public class Result {
    private String code;
    private String msg;
    private Object body;

    public Result() {
    }

    public Result(String code, String msg, Object body) {
        this.code = code;
        this.msg = msg;
        this.body = body;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getBody() {
        return body;
    }

    public void setBody(Object body) {
        this.body = body;
    }

    public static Result gen(String code, String msg, Object data) {
        return new Result(code, msg, data);
    }

    public static Result gen(ErrorType type, Object data) {
        return new Result(type.getCode(), type.getMsg(), data);
    }

    public static Result ok() {
        return gen(ErrorType.Succ, null);
    }

    public static Result ok(Object data) {
        return gen(ErrorType.Succ, data);
    }

    public static Result fail(String msg) {
        return new Result(ErrorType.Fail.getCode(), msg, null);
    }
}

ErrorType

package com.soft.exception;


public enum ErrorType {
    Succ("0","操作成功"),
    Fail("1","操作失败"),
    ReqParamMissing("0001","请求参数缺少"),
    DataNotExist("1000","数据不存在"),
    DataExist("1001","数据已存在"),
    InvalidQuery("1002","无效的查询"),
    InvalidMod("1003","无效的修改"),
    SysErr("9999","系统错误");

    private String code;
    private String msg;

    ErrorType(String code,String msg) {
        this.code=code;
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

ServerConf

package com.soft.config;

import cn.hutool.setting.Setting;

public class ServerConf {
    private static final Setting SETTING = new Setting("server.setting");
    public static final ServerVo VO = SETTING.toBean(ServerVo.class);

    private ServerConf() {
    }

}

ServerVo:

package com.soft.config;

import lombok.Data;

@Data
public class ServerVo {
    private int port;
    private String contextPath;
    private String resourceBase;
	private int maxThreads;
	private String ipWhiteList;// 逗号分隔ip
}

User:

package com.soft.po;

import java.util.Date;

import lombok.Data;

@Data
public class User {
    private String username;
	private int age;
    private int status;
	private Date moddate;

}

server.setting:

port=8080
contextPath=/
[email protected]_HOME@/conf
maxThreads=30
ipWhiteList=


 

你可能感兴趣的:(java,jersey,jetty,restful)