# DbPoxy代理服务

测试DbPoxy功能即以本书中的 《程序安装》章节为例。展示如何通过Coolpy Gen Protocol（IOT通用控制协议）测试最简单的对mongodb数据库进行插入、查询、修改、删除数据操作。

### 先决条件

1. 按《程序安装》章节部署整套CP7平台
2. 按《消息通信功能测试》章节安装MQTTLens通信测试工具

### 开始测试

CP7 DbPoxy代理服务器配置文件

```
#mongodb
DatabaseType: mongodb
DatabaseConnectionString: mongodb://192.168.200.250:27017
#CP7 Core服务相关连接信息
BrokerHost: 192.168.100.2
BrokerPort: 1883
#如果部署不同的DbPoxy服务需要更改以下的Clientid为唯一
BrokerClientId: dbpoxy
#CP7 Core服务身份验证信息
BrokerUser: dypoxy
BrokerPassword: dypoxy
#相关杂项配置
BrokerClearSession: true
LogFilePath: dbpoxy.log
#当控制消息(CGP)到来时进行口令验证，此token一至才允许协议消息执行
AccessToken: password
#当前DbPoxy节点所使用的接收消息主题（topic)及消息质量(qos)
OpTopics:
 Topic: dbpoxy/mongodb/get
 Qos: 0
```

运行DbPoxy

```
2018/11/08 10:13:37 mongodb ping ok
2018/11/08 10:13:37 Coolpy7_db_poxy.go:77: dbpoxy/mongodb/get OK, token: password
```

以上信息已表达连接mongodb数据库ping成功，说明连接已成功建立。第二行提示：DbPoxy所在主题为dbpoxy/mongodb/get。操作密令为：password

#### 向数据库插入一条数据记录

```
{
"db_name":"DbPoxyTestDB",
"table_name":"test",
"op_name":"insert",
"token":"password",
"msg_id":1,
"ref_topic":"dbpoxy/mongodb/result",
"ref_qos":0,
"value":{"datetime":"2018-10-12T10:10:12+08:00","number":12345.12345655889977,"string":"djkfjdkfj" }
}
```

上文是Coolpy Gen Protocol(CGP)协议之一，向数据库发起插入一条新记录操作。（此应用在IOT领域最常用的场境是传感器数据上传到数据库中保存）

| CGP协议名      | 数据类型        | 说明                                                                                                |
| ----------- | ----------- | ------------------------------------------------------------------------------------------------- |
| db\_name    | string      | 数据库名称（如数据库名不存在DbPoxy会自动创建)                                                                        |
| table\_name | string      | 数据库表名称（如不存在会自动创建)                                                                                 |
| op\_name    | string      | 数据操作符（insert，delete，update，query)分别是增删改查                                                          |
| token       | string      | 鉴权口令，与DbPoxy配置文件中的AccessToken一至才能被执行                                                              |
| msg\_id     | int64       | 执行结果回传时会跟随一起把此项原封不动带回，此功能在多消息操作后区分回调消息对应的操作而设计                                                    |
| ref\_topic  | string      | 执行结果回调主题，当执行完成或执行出错会把结果发送到此主题，消息编码同时支持json及msgpack两种，当DbPoxy在尝试解码出错的情况下不会有任何错误提示返回，原因是此回调主题在消息体内。 |
| ref\_qos    | int         | 回调主题消息质量标识（0,1,2)                                                                                 |
| value       | json/string | 需插入数据库的数据内容，当mongodb时间为json类型，当sql数据库时为string类型的sql语句                                             |

{% hint style="info" %}
在发送指令前需在当前连接订阅消息中以消息质量控制ref\_qos订阅ref\_topic主题，用以接收指令执行结果回传消息通知。
{% endhint %}

![](/files/-LQlExZarPf7PzIzOtcj)

以上操作说明：

1.填写Publish主题为DbPoxy配置文件中的Topic值，并以配置文件的qos为消息质量控制

```
OpTopics:
 Topic: dbpoxy/mongodb/get
 Qos: 0
```

2.填写CGP协议消息，插入一条记录到数据库

```
{
"db_name":"DbPoxyTestDB",
"table_name":"test",
"op_name":"insert",
"token":"password",
"msg_id":1,
"ref_topic":"dbpoxy/mongodb/result",
"ref_qos":0,
"value":{"datetime":"2018-10-12T10:10:12+08:00","number":12345.12345655889977,"string":"djkfjdkfj" }
}
```

3.订阅指令执行结果回调主题，并以qos一致控制消息质量

```
"ref_topic":"dbpoxy/mongodb/result",
"ref_qos":0,
```

4.点击PUBLISH按扭发送指令到DbPoxy。DbPoxy收到指令后会按协议内容执行，结果会推送到ref\_topic主题。

5.接收到执行结果，消息id及操作结果

```
{
  "msg_id": 1,
  "result_op": true,
  "result_changes": 1,
  "result_data": [
    "5be3a553572c066aa453f8c6"
  ]
}
```

| CGP协议名          | 数据类型                 | 说明                                                                     |
| --------------- | -------------------- | ---------------------------------------------------------------------- |
| msg\_id         | int64                | 指令自身id标识，回发接收到执行指令中的内容                                                 |
| result\_op      | bool                 | 操作是否成功，true为成功，false为失败                                                |
| result\_changes | int64                | 操作影响了多少条数据库记录                                                          |
| result\_data    | \[]objectid/\[]int64 | 操作返回有价值结果内容，本例中返回的是插入记录的mongoid新记录的ObjectId数组，如果为sql数据库会返回int64新数据记录ID |

### 验证数据是否写入数据库

![](/files/-LQlIdCAx7wUUqjMPOt5)

本例使用NosqlBooster连接到mongodb数据库，并查验本例操作中的添加的两条数据库记录正常。

### 完整dbpoxy.yml配置文件示例

```
#mongodb
#DatabaseType: mongodb
#DatabaseConnectionString: mongodb://localhost:27017

#postgres
#DatabaseType: postgres #mssql mysql postgres
#DatabaseConnectionString: host=192.168.100.187 port=13246 user=postgres dbname=ldh sslmode=disable password=123456

#mysql
DatabaseType: mysql #mssql mysql postgres
DatabaseConnectionString: "root:123456@/ldh?charset=utf8"

#oss
#DatabaseType: oss-gridfs
#DatabaseConnectionString: mongodb://127.0.0.1:27017

BrokerHost: 127.0.0.1
BrokerPort: 1883
BrokerClientId: dbpoxy
BrokerUser: dypoxy
BrokerPassword: dypoxy
BrokerClearSession: true
LogFilePath: dbpoxy.log
AccessToken: password
OpTopics:
 Topic: dbpoxy/mongodb/get
 Qos: 0
```

## 更多请查阅《CGP协议》章节


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coolpy7.gitbook.io/coolpy7book/kai-shi-shi-yong/dbpoxy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
