Vertx构建Restful API

  • Verticle实现类ServiceVerticle
public class ServiceVerticle extends AbstractVerticle
{
	private static final int CORE_NUM = 2;

	public static void main(String[] args)
	{
		Vertx vertx = Vertx.vertx();
		DeploymentOptions deploymentOptions = new DeploymentOptions()
				.setWorker(true)
				.setInstances(CORE_NUM)
				.setWorkerPoolSize(CORE_NUM)
				.setWorkerPoolName("vertx-thread-pool");

		vertx.deployVerticle(ServiceVerticle.class, deploymentOptions, asyncResult ->
		{
			if (asyncResult.failed())
			{
				System.out.println("Start server failed!");
			}
			else
			{
				System.out.println("Start server success!");
			}
		});
	}

	@Override
	public void start(Future<Void> startFuture) throws Exception
	{
		JksOptions jksOptions = new JksOptions().setPath("localhost.jks").setPassword("localhost");
		HttpServerOptions options = new HttpServerOptions().setSsl(true).setKeyStoreOptions(jksOptions);
		HttpServer server = vertx.createHttpServer(options);

		Router router = Router.router(vertx);
		// We need request bodies
		router.route().handler(BodyHandler.create());
		// We consume application/json, also produce it
		router.route().consumes("application/json").produces("application/json");
		// Register API
		registerResource(router);

		// Start the HTTPS server
		server.requestHandler(router::accept).listen(8080, asyncResult ->
		{
			if (asyncResult.failed())
			{
				System.out.println("start server failed! " + asyncResult.cause());
			}
			else
			{
				System.out.println("start server success!");
			}
		});
	}

	private void registerResource(Router router)
	{
		DemoResource demoResource = new DemoResource();
		demoResource.registerResource(router);
	}

}
  • API接口类
public class DemoResource extends BaseResource
{
	// 省略部分代码
	
	@Override
	public void registerResource(Router router)
	{
		router.get(VERSION +"/resource/:resource_id").handler(this::queryResource).failureHandler(this::failedHandler);
		router.get(VERSION + "/resource").handler(this::queryAllResource).failureHandler(this::failedHandler);
		router.post(VERSION + "/resource").handler(this::createResource).failureHandler(this::failedHandler);
	}
}

代码Github地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值