设为首页 收藏本站
查看: 641|回复: 0

[经验分享] 启动jetty方式

[复制链接]

尚未签到

发表于 2017-2-25 13:29:46 | 显示全部楼层 |阅读模式
  一、不使用jetty.xml配置文件启动

package hb.test.jetty;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.xml.sax.SAXException;
public class SimpleServerStart {
public static void main(String[] args) {
try {
// 服务器的监听端口
Server server = new Server(8080);
// 关联一个已经存在的上下文
WebAppContext context = new WebAppContext();
// 设置描述符位置
context.setDescriptor("./web/WEB-INF/web.xml");
// 设置Web内容上下文路径
context.setResourceBase("./web");
// 设置上下文路径
context.setContextPath("/myproject");
context.setParentLoaderPriority(true);
server.setHandler(context);
// 启动
server.start();
server.join();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

  二、通过配置文件启动jetty

package hb.test.jetty;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.xml.XmlConfiguration;
import org.xml.sax.SAXException;
public class SimpleServerConfig {
public static void main(String[] args) {
try {
// 创建一个默认服务器对象
Server server = new Server();
// server.setHandler(new DefaultHandler());
// 初始化server对象的属性,这些属性全部来至于xmlconfig文件的配置,有点类似于spring通过配置文件获取对象
XmlConfiguration config = new XmlConfiguration(new FileInputStream("./jetty/etc/jetty.xml"));
config.configure(server);
// 给创建的server服务器配置处理的handler对象,可以通过xmlconfig配置,也可以手动配置,下面代码是手动配置完成的
ContextHandlerCollection handler = new ContextHandlerCollection();
// 创建一个webapp对象
WebAppContext webapp = new WebAppContext();
// 一定要有反斜杠,表示当前工程的上下文
webapp.setContextPath("/myjetty");
webapp.setDefaultsDescriptor("./jetty/etc/webdefault.xml");
webapp.setResourceBase("./web");
webapp.setDescriptor("./web/WEB-INF/web.xml");
handler.addHandler(webapp);
server.setHandler(handler);
server.start();
server.join();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

  配置jetty.xml文件,使用jetty9,需要添加如下标签

    <Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<Item>
<New class="org.eclipse.jetty.server.HttpConnectionFactory">
<Arg name="config"><Ref refid="httpConfig" /></Arg>
</New>
</Item>
</Array>
</Arg>
<Set name="host"><Property name="jetty.host" /></Set>
<Set name="port"><Property name="jetty.port" default="8080" /></Set>
<Set name="idleTimeout">30000</Set>
</New>
</Arg>
</Call>


<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<!-- =============================================================== -->
<!-- Documentation of this file format can be found at:              -->
<!-- http://wiki.eclipse.org/Jetty/Reference/jetty.xml_syntax        -->
<!--                                                                 -->
<!-- Additional configuration files are available in $JETTY_HOME/etc -->
<!-- and can be mixed in. See start.ini file for the default         -->
<!-- configuration files.                                            -->
<!--                                                                 -->
<!-- For a description of the configuration mechanism, see the       -->
<!-- output of:                                                      -->
<!--   java -jar start.jar -?                                        -->
<!-- =============================================================== -->
<!-- =============================================================== -->
<!-- Configure a Jetty Server instance with an ID "Server"           -->
<!-- Other configuration files may also configure the "Server"       -->
<!-- ID, in which case they are adding configuration to the same     -->
<!-- instance.  If other configuration have a different ID, they     -->
<!-- will create and configure another instance of Jetty.            -->
<!-- Consult the javadoc of o.e.j.server.Server for all              -->
<!-- configuration that may be set here.                             -->
<!-- =============================================================== -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<!-- =========================================================== -->
<!-- Configure the Server Thread Pool.                           -->
<!-- The server holds a common thread pool which is used by      -->
<!-- default as the executor used by all connectors and servlet  -->
<!-- dispatches.                                                 -->
<!--                                                             -->
<!-- Configuring a fixed thread pool is vital to controlling the -->
<!-- maximal memory footprint of the server and is a key tuning  -->
<!-- parameter for tuning.  In an application that rarely blocks -->
<!-- then maximal threads may be close to the number of 5*CPUs.  -->
<!-- In an application that frequently blocks, then maximal      -->
<!-- threads should be set as high as possible given the memory  -->
<!-- available.                                                  -->
<!--                                                             -->
<!-- Consult the javadoc of o.e.j.util.thread.QueuedThreadPool   -->
<!-- for all configuration that may be set here.                 -->
<!-- =========================================================== -->
<Arg name="threadpool">
<New id="threadpool" class="org.eclipse.jetty.util.thread.QueuedThreadPool">
<Arg name="minThreads" type="int">10</Arg>
<Arg name="maxThreads" type="int">200</Arg>
<Arg name="idleTimeout" type="int">60000</Arg>
<Set name="detailedDump">false</Set>
</New>
</Arg>
<!-- =========================================================== -->
<!-- Add shared Scheduler instance                               -->
<!-- =========================================================== -->
<Call name="addBean">
<Arg>
<New class="org.eclipse.jetty.util.thread.ScheduledExecutorScheduler"/>
</Arg>
</Call>
<!-- =========================================================== -->
<!-- Http Configuration.                                         -->
<!-- This is a common configuration instance used by all         -->
<!-- connectors that can carry HTTP semantics (HTTP, HTTPS, SPDY)-->
<!-- It configures the non wire protocol aspects of the HTTP     -->
<!-- semantic.                                                   -->
<!--                                                             -->
<!-- This configuration is only defined here and is used by      -->
<!-- reference from the jetty-http.xml, jetty-https.xml and      -->
<!-- jetty-spdy.xml configuration files which instantiate the    -->
<!-- connectors.                                                 -->
<!--                                                             -->
<!-- Consult the javadoc of o.e.j.server.HttpConfiguration       -->
<!-- for all configuration that may be set here.                 -->
<!-- =========================================================== -->
<New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Set name="secureScheme">https</Set>
<Set name="securePort"><Property name="jetty.secure.port" default="8443" /></Set>
<Set name="outputBufferSize">32768</Set>
<Set name="requestHeaderSize">8192</Set>
<Set name="responseHeaderSize">8192</Set>
<Set name="sendServerVersion">true</Set>
<Set name="sendDateHeader">false</Set>
<Set name="headerCacheSize">512</Set>
<!-- Uncomment to enable handling of X-Forwarded- style headers
<Call name="addCustomizer">
<Arg><New class="org.eclipse.jetty.server.ForwardedRequestCustomizer"/></Arg>
</Call>
-->
</New>
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<Item>
<New class="org.eclipse.jetty.server.HttpConnectionFactory">
<Arg name="config"><Ref refid="httpConfig" /></Arg>
</New>
</Item>
</Array>
</Arg>
<Set name="host"><Property name="jetty.host" /></Set>
<Set name="port"><Property name="jetty.port" default="8080" /></Set>
<Set name="idleTimeout">30000</Set>
</New>
</Arg>
</Call>

<!-- =========================================================== -->
<!-- Set the default handler structure for the Server            -->
<!-- A handler collection is used to pass received requests to   -->
<!-- both the ContextHandlerCollection, which selects the next   -->
<!-- handler by context path and virtual host, and the           -->
<!-- DefaultHandler, which handles any requests not handled by   -->
<!-- the context handlers.                                       -->
<!-- Other handlers may be added to the "Handlers" collection,   -->
<!-- for example the jetty-requestlog.xml file adds the          -->
<!-- RequestLogHandler after the default handler                 -->
<!-- =========================================================== -->
<Set name="handler">
<New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
<Set name="handlers">
<Array type="org.eclipse.jetty.server.Handler">
<Item>
<New id="Contexts" class="org.eclipse.jetty.server.handler.ContextHandlerCollection"/>
</Item>
<Item>
<New id="DefaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler"/>
</Item>
</Array>
</Set>
</New>
</Set>
<!-- =========================================================== -->
<!-- extra server options                                        -->
<!-- =========================================================== -->
<Set name="stopAtShutdown">true</Set>
<Set name="stopTimeout">5000</Set>
<Set name="dumpAfterStart">false</Set>
<Set name="dumpBeforeStop">false</Set>
</Configure>

  三,自定义server启动jetty

package hb.test.jetty;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.xml.XmlConfiguration;
import org.xml.sax.SAXException;
public class JettyCustomServer extends Server {
private String xmlConfigPath;
private String contextPath;
private String warPath;
private String resourceBase = "./web";
private String webXmlPath = "./web/WEB-INF/web.xml";
public JettyCustomServer(String xmlConfigPath, String contextPath,
String resourceBase, String webXmlPath) {
this(xmlConfigPath, contextPath, resourceBase, webXmlPath, null);
}
public JettyCustomServer(String xmlConfigPath, String contextPath) {
this(xmlConfigPath, contextPath, null, null, null);
}
public JettyCustomServer(String xmlConfigPath, String contextPath,
String warPath) {
this(xmlConfigPath, contextPath, null, null, warPath);
}
public JettyCustomServer(String xmlConfigPath, String contextPath,
String resourceBase, String webXmlPath, String warPath) {
super();
if (StringUtils.isNotBlank(xmlConfigPath)) {
this.xmlConfigPath = xmlConfigPath;
readXmlConfig();
}
//判断是否是根据jetty的发布目录启动工程
if (StringUtils.isNotBlank(warPath)) {
this.warPath = warPath;
if (StringUtils.isNotBlank(contextPath)) {
this.contextPath = contextPath;
applyHandle(true);
}
} else {//自定义web工程的上下文及工程所在的位置
if (StringUtils.isNotBlank(resourceBase))
this.resourceBase = resourceBase;
if (StringUtils.isNotBlank(webXmlPath))
this.webXmlPath = webXmlPath;
if (StringUtils.isNotBlank(contextPath)) {
this.contextPath = contextPath;
applyHandle(false);
}
}
}
/**
*
* @param warDeployFlag
*/
public void applyHandle(Boolean warDeployFlag) {
ContextHandlerCollection handler = new ContextHandlerCollection();
WebAppContext webapp = new WebAppContext();
webapp.setContextPath(contextPath);
webapp.setDefaultsDescriptor("./jetty/etc/webdefault.xml");
if (!warDeployFlag) {
webapp.setResourceBase(resourceBase);
webapp.setDescriptor(webXmlPath);
} else {
webapp.setWar(warPath);
}
handler.addHandler(webapp);
super.setHandler(handler);
}
public void readXmlConfig() {
try {
XmlConfiguration config = new XmlConfiguration(new FileInputStream(
this.xmlConfigPath));
config.configure(this);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void startServer() {
try {
super.start();
System.out.println("current thread:"
+ super.getThreadPool().getThreads() + "| idle thread:"
+ super.getThreadPool().getIdleThreads());
super.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getXmlConfigPath() {
return xmlConfigPath;
}
public void setXmlConfigPath(String xmlConfigPath) {
this.xmlConfigPath = xmlConfigPath;
}
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public String getWarPath() {
return warPath;
}
public void setWarPath(String warPath) {
this.warPath = warPath;
}
public String getResourceBase() {
return resourceBase;
}
public void setResourceBase(String resourceBase) {
this.resourceBase = resourceBase;
}
public String getWebXmlPath() {
return webXmlPath;
}
public void setWebXmlPath(String webXmlPath) {
this.webXmlPath = webXmlPath;
}
}


package hb.test.jetty;
public class JettyServerStart {
public static void main(String[] args) {
JettyCustomServer server = new JettyCustomServer("./jetty/etc/jetty.xml","/testContext");
server.startServer();
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-347120-1-1.html 上篇帖子: MAVEN配置jetty 下篇帖子: jetty 配置集群
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表