分布式数据库中间件–(2) Cobar与客户端的握手认证
Cobar启动完成,监听特定端口。整个认证的流程图: NIOAcceptor类继承自Thread类,该类的对象会以线程的方式运行,进行连接的监听。NIOAcceptor启动的初始化过程如下:1 、打开一个selector,获取一个ServerSocketChannel对象,对该对象的socket绑定特定的监
Cobar启动完成,监听特定端口。整个认证的流程图:
public NIOAcceptor(String name, int port, FrontendConnectionFactory factory) throws IOException { super.setName(name); this.port = port; this.selector = Selector.open(); this.serverChannel = ServerSocketChannel.open(); //ServerSocket使用TCP this.serverChannel.socket().bind(new InetSocketAddress(port)); this.serverChannel.configureBlocking(false); this.serverChannel.register(selector, SelectionKey.OP_ACCEPT); this.factory = factory; }
public void run() { final Selector selector = this.selector; //线程一直循环 for (;;) { ++acceptCount; try { selector.select(1000L); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { if (key.isValid() && key.isAcceptable()) { //接受来自客户端的连接 accept(); } else { key.cancel(); } } } finally { keys.clear(); } } catch (Throwable e) { LOGGER.warn(getName(), e); } } }
- interest集合(使用&操作SelectionKey.OP_ACCEPT和key.interestOps())
- ready集合(key.readyOps(),可以使用&操作检测该集合,也可以使用is方法)
- Channel(key.channel())
- Selector(key.selector())
- 附加对象(key.attach(obj) ? Object obj = key.attachment())
private void accept() { SocketChannel channel = null; try { //从服务器端获取管道,为一个新的连接返回channel channel = serverChannel.accept(); //配置管道为非阻塞 channel.configureBlocking(false); //前端连接工厂对管道进行配置,设置socket的收发缓冲区大小,TCP延迟等 //然后由成员变量factory的类型生产对于的类型的连接 //比如ServerConnectionFactory会返回ServerConnection实例,并对其属性进行设置 FrontendConnection c = factory.make(channel); //设置连接属性 c.setAccepted(true); c.setId(ID_GENERATOR.getId()); //从processors中选择一个NIOProcessor,将其和该连接绑定 NIOProcessor processor = nextProcessor(); c.setProcessor(processor); //向读反应堆注册该连接,加入待处理队列 //select选择到感兴趣的事件后,会进行调用connection的read函数 processor.postRegister(c); } catch (Throwable e) { closeChannel(channel); LOGGER.warn(getName(), e); } }

public void run() { final Selector selector = this.selector; for (;;) { ++reactCount; try { int res = selector.select(); LOGGER.debug(reactCount + ">>NIOReactor接受连接数:" + res); register(selector); Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { Object att = key.attachment(); if (att != null && key.isValid()) { int readyOps = key.readyOps(); if ((readyOps & SelectionKey.OP_READ) != 0) { LOGGER.debug("select读事件"); read((NIOConnection) att); } else if ((readyOps & SelectionKey.OP_WRITE) != 0) { LOGGER.debug("select写事件"); write((NIOConnection) att); } else { key.cancel(); } } else { key.cancel(); } } } finally { keys.clear(); } } catch (Throwable e) { LOGGER.warn(name, e); } } }
?channel.register(selector, SelectionKey.OP_READ, this);注意最后一个this指针参数,表示将该连接作为附件,注册到selector,当有感兴趣的时间发生时,函数selector.selectedKeys()返回的SelectionKey集合中的对象中使用key.attachment()即可获取到上面注册时绑定的connection对象指针附件。目的就是为了通过该附件对象调用该连接类中定义的read函数来完成功能。如下所示:
private void read(NIOConnection c) { try { c.read(); } catch (Throwable e) { c.error(ErrorCode.ERR_READ, e); } }
public void handle(final byte[] data) { // 从线程池获取一个线程,异步处理前端数据 // 从processor中的线程池中获取一个可以执行的线程,执行Runnable任务 processor.getHandler().execute(new Runnable() { @Override public void run() { try { //调用具体NIOHandler子类的handle函数 handler.handle(data); } catch (Throwable t) { error(ErrorCode.ERR_HANDLE_DATA, t); } } }); }
public FrontendConnection(SocketChannel channel) { super(channel); ..................... //前端认证处理器 this.handler = new FrontendAuthenticator(this); }


- 读取信息到认证包对象
- 核对用户
- 核对密码
- 检查schema
public void handle(byte[] data) { // check quit packet if (data.length == QuitPacket.QUIT.length && data[4] == MySQLPacket.COM_QUIT) { source.close(); return; } //新建认证包对象 AuthPacket auth = new AuthPacket(); //读取认证包到对象 auth.read(data); // check user if (!checkUser(auth.user, source.getHost())) { failure(ErrorCode.ER_ACCESS_DENIED_ERROR, "Access denied for user '" + auth.user + "'"); return; } // check password if (!checkPassword(auth.password, auth.user)) { failure(ErrorCode.ER_ACCESS_DENIED_ERROR, "Access denied for user '" + auth.user + "'"); return; } // check schema switch (checkSchema(auth.database, auth.user)) { case ErrorCode.ER_BAD_DB_ERROR: failure(ErrorCode.ER_BAD_DB_ERROR, "Unknown database '" + auth.database + "'"); break; case ErrorCode.ER_DBACCESS_DENIED_ERROR: String s = "Access denied for user '" + auth.user + "' to database '" + auth.database + "'"; failure(ErrorCode.ER_DBACCESS_DENIED_ERROR, s); break; default: //认证成功,向客户端发送认证结果消息 success(auth); } }
protected void success(AuthPacket auth) { //认证通过,设置连接属性:已认证\用户\数据库\处理器 source.setAuthenticated(true); source.setUser(auth.user); source.setSchema(auth.database); source.setCharsetIndex(auth.charsetIndex); //设置该连接的连接处理器为前端命令处理器 source.setHandler(new FrontendCommandHandler(source)); ....... ByteBuffer buffer = source.allocate(); source.write(source.writeToBuffer(AUTH_OK, buffer)); }
16:59:19,388 INFO =============================================== 16:59:19,389 INFO Cobar is ready to startup ... 16:59:19,389 INFO Startup processors ... 16:59:19,455 INFO Startup connector ... 16:59:19,460 INFO Initialize dataNodes ... 16:59:19,506 INFO dnTest1:0 init success 16:59:19,514 INFO dnTest3:0 init success 16:59:19,517 INFO dnTest2:0 init success 16:59:19,527 INFO CobarServer is started and listening on 8066 16:59:19,527 INFO =============================================== 16:59:23,459 DEBUG 1>>NIOReactor接受连接数:0 16:59:23,464 DEBUG 2>>NIOReactor接受连接数:1 16:59:23,465 DEBUG select读事件 16:59:23,465 INFO com.alibaba.cobar.net.handler.FrontendAuthenticator接收的请求长度:62 58 0 0 1 5 166 15 0 0 0 0 1 33 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 114 111 111 116 0 20 169 171 247 102 133 96 158 224 121 22 226 229 88 244 119 238 185 61 124 219 16:59:23,468 INFO [thread=Processor1-H0,class=ServerConnection,host=192.168.137.8,port=46101,schema=null]'root' login success
yan@yan-Z400:~$ mysql -uroot -p** -P8066 -h192.168.137.8 Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 1 Server version: 5.1.48-cobar-1.2.7 Cobar Server (ALIBABA) Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>
本文出自:http://blog.geekcome.com, 原文地址:http://blog.geekcome.com/%e5%88%86%e5%b8%83%e5%bc%8f%e6%95%b0%e6%8d%ae%e5%ba%93%e4%b8%ad%e9%97%b4%e4%bb%b6-2-cobar%e4%b8%8e%e5%ae%a2%e6%88%b7%e7%ab%af%e7%9a%84%e6%8f%a1%e6%89%8b%e8%ae%a4%e8%af%81, 感谢原作者分享。

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

蘋果公司最新發布的iOS18、iPadOS18以及macOSSequoia系統為Photos應用程式增添了一項重要功能,旨在幫助用戶輕鬆恢復因各種原因遺失或損壞的照片和影片。這項新功能在Photos應用的"工具"部分引入了一個名為"已恢復"的相冊,當用戶設備中存在未納入其照片庫的圖片或影片時,該相冊將自動顯示。 "已恢復"相簿的出現為因資料庫損壞、相機應用未正確保存至照片庫或第三方應用管理照片庫時照片和視頻丟失提供了解決方案。使用者只需簡單幾步

PHP處理資料庫連線報錯,可以使用下列步驟:使用mysqli_connect_errno()取得錯誤代碼。使用mysqli_connect_error()取得錯誤訊息。透過擷取並記錄這些錯誤訊息,可以輕鬆識別並解決資料庫連接問題,確保應用程式的順暢運作。

如何在PHP中使用MySQLi建立資料庫連線:包含MySQLi擴充(require_once)建立連線函數(functionconnect_to_db)呼叫連線函數($conn=connect_to_db())執行查詢($result=$conn->query())關閉連線( $conn->close())

在Golang中使用資料庫回呼函數可以實現:在指定資料庫操作完成後執行自訂程式碼。透過單獨的函數新增自訂行為,無需編寫額外程式碼。回調函數可用於插入、更新、刪除和查詢操作。必須使用sql.Exec、sql.QueryRow或sql.Query函數才能使用回呼函數。

可以透過使用gjson函式庫或json.Unmarshal函數將JSON資料儲存到MySQL資料庫中。 gjson函式庫提供了方便的方法來解析JSON字段,而json.Unmarshal函數需要一個目標類型指標來解組JSON資料。這兩種方法都需要準備SQL語句和執行插入操作來將資料持久化到資料庫中。

在C++中使用DataAccessObjects(DAO)函式庫連接和操作資料庫,包括建立資料庫連線、執行SQL查詢、插入新記錄和更新現有記錄。具體步驟為:1.包含必要的函式庫語句;2.開啟資料庫檔案;3.建立Recordset物件執行SQL查詢或操作資料;4.遍歷結果或依照特定需求更新記錄。

透過Go標準庫database/sql包,可以連接到MySQL、PostgreSQL或SQLite等遠端資料庫:建立包含資料庫連接資訊的連接字串。使用sql.Open()函數開啟資料庫連線。執行SQL查詢和插入操作等資料庫操作。使用defer關閉資料庫連線以釋放資源。

PHP連接資料庫指南:MySQL:安裝MySQLi擴展,建立連線(servername、username、password、dbname)。 PostgreSQL:安裝PgSQL擴展,建立連線(host、dbname、user、password)。 Oracle:安裝OracleOCI8擴展,建立連線(servername、username、password)。實戰案例:取得MySQL資料、PostgreSQL查詢、OracleOCI8更新記錄。
