是否可以通过Java NIO非阻塞套接字异步访问数据库? [英] Is it possible to access a database asynchronously through Java NIO non-blocking sockets?

查看:476
本文介绍了是否可以通过Java NIO非阻塞套接字异步访问数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以非阻塞的方式访问数据库,换句话说,我将通过套接字发送SQL请求,并通过相同的套接字异步读取查询响应。这意味着我只在套接字可用时读取数据(Java NIO SocketChannel )所以我从不阻止。



<我可能错了,但据我所知,数据库的JDBC驱动程序都使用阻塞套接字。



即使我必须执行返回100万行的查询,我可以异步地执行此操作,接收在套接字缓冲区中可用的行。



我的目标是执行SQL查询而不会阻塞(即没有产生延迟) 。 使用单独的线程不是一个选项。我需要在网络线程(NIO选择器线程)中执行此操作。



是否有人成功执行此操作或建议不涉及额外线程的方法?

解决方案

这是可能的,但不适用于JDBC。除非您想使用原始 SocketChannel 接口并自行解析结果,否则我知道的JVM上唯一的异步数据库驱动程序是 https://github.com/mauricio/postgresql-async (尽管名称也支持MySQL)。它们是用Scala编写的,但它应该可能从Java调用它们(因为它是一种JVM语言),但我不能说它对API有多友好。


I would like to access a database in a non-blocking way, in other words, I will send the SQL request through a socket and read the query response through the same socket asynchronously. That means that I only read data from the socket as it becomes available (Java NIO SocketChannel) so I never block.

I might be wrong but as far as I know JDBC drivers for databases all use blocking sockets.

Even if I have to execute a query that returns 1 million lines, I can do that asynchronously, receiving lines as they become available in the socket buffer.

My goal is to execute an SQL query without ever blocking (i.e. without ever producing latency). Using a separate thread is not an option. I need to do that inside the network thread (NIO selector thread).

Has anyone succeeded in doing this or can recommend an approach that does not involve an extra thread?

解决方案

It's possible, but not with JDBC. Unless you want to use the raw SocketChannel interface and parse the results yourself, the only async database drivers on the JVM I'm aware of are https://github.com/mauricio/postgresql-async (which despite the name also supports MySQL). They're written in Scala but it should be possible to call them from Java (since it's a JVM language), though I can't say how Java-friendly the API will be.

这篇关于是否可以通过Java NIO非阻塞套接字异步访问数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆