Skip to content

Commit e06b883

Browse files
authored
Merge pull request #9 from aliyun/dev
Add example of pagination read.
2 parents fa64836 + e133d77 commit e06b883

File tree

1 file changed

+197
-0
lines changed

1 file changed

+197
-0
lines changed
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
package examples;
2+
3+
import com.aliyun.openservices.ots.*;
4+
import com.aliyun.openservices.ots.model.*;
5+
import com.aliyun.openservices.ots.utils.Preconditions;
6+
import javafx.util.Pair;
7+
8+
import java.util.ArrayList;
9+
import java.util.List;
10+
11+
public class OTSPaginationReadSample {
12+
private static final String COLUMN_GID_NAME = "gid";
13+
private static final String COLUMN_UID_NAME = "uid";
14+
private static final String COLUMN_NAME_NAME = "name";
15+
private static final String COLUMN_ADDRESS_NAME = "address";
16+
private static final String COLUMN_AGE_NAME = "age";
17+
private static final String COLUMN_MOBILE_NAME = "mobile";
18+
19+
public static void main(String args[]) {
20+
final String endPoint = "";
21+
final String accessId = "";
22+
final String accessKey = "";
23+
final String instanceName = "";
24+
25+
OTSClient client = new OTSClient(endPoint, accessId, accessKey,
26+
instanceName);
27+
final String tableName = "sampleTable";
28+
29+
try {
30+
// 创建表
31+
createTable(client, tableName);
32+
33+
// 注意:创建表只是提交请求,OTS创建表需要一段时间。
34+
// 这里简单地等待5秒,请根据您的实际逻辑修改。
35+
Thread.sleep(5000);
36+
37+
// 插入多行数据。
38+
putRows(client, tableName);
39+
40+
// 分页查询数据,每一页取5条,直到全部查完.
41+
readByPage(client, tableName);
42+
} catch (ServiceException e) {
43+
System.err.println("操作失败,详情:" + e.getMessage());
44+
// 可以根据错误代码做出处理, OTS的ErrorCode定义在OTSErrorCode中。
45+
if (OTSErrorCode.QUOTA_EXHAUSTED.equals(e.getErrorCode())) {
46+
System.err.println("超出存储配额。");
47+
}
48+
// Request ID可以用于有问题时联系客服诊断异常。
49+
System.err.println("Request ID:" + e.getRequestId());
50+
} catch (ClientException e) {
51+
// 可能是网络不好或者是返回结果有问题
52+
System.err.println("请求失败,详情:" + e.getMessage());
53+
} catch (InterruptedException e) {
54+
System.err.println(e.getMessage());
55+
} finally {
56+
// 不留垃圾。
57+
try {
58+
deleteTable(client, tableName);
59+
} catch (ServiceException e) {
60+
System.err.println("删除表格失败,原因:" + e.getMessage());
61+
e.printStackTrace();
62+
} catch (ClientException e) {
63+
System.err.println("删除表格请求失败,原因:" + e.getMessage());
64+
e.printStackTrace();
65+
}
66+
client.shutdown();
67+
}
68+
}
69+
70+
/**
71+
* 范围查询指定范围内的数据,返回指定页数大小的数据,并能根据offset跳过部分行。
72+
*/
73+
private static Pair<List<Row>, RowPrimaryKey> readByPage(OTSClient client, String tableName, RowPrimaryKey startKey, RowPrimaryKey endKey, int offset, int pageSize) {
74+
Preconditions.checkArgument(offset >= 0, "Offset should not be negative.");
75+
Preconditions.checkArgument(pageSize > 0, "Page size should be greater than 0.");
76+
77+
List<Row> rows = new ArrayList<Row>(pageSize);
78+
int limit = pageSize;
79+
int skip = offset;
80+
81+
RowPrimaryKey nextStart = startKey;
82+
while (limit > 0 && nextStart != null) {
83+
RangeRowQueryCriteria criteria = new RangeRowQueryCriteria(tableName);
84+
criteria.setInclusiveStartPrimaryKey(nextStart);
85+
criteria.setExclusiveEndPrimaryKey(endKey);
86+
criteria.setLimit(skip + limit);
87+
88+
GetRangeRequest request = new GetRangeRequest();
89+
request.setRangeRowQueryCriteria(criteria);
90+
GetRangeResult response = client.getRange(request);
91+
for (Row row : response.getRows()) {
92+
if (skip > 0) {
93+
skip--;
94+
} else {
95+
rows.add(row);
96+
limit--;
97+
}
98+
}
99+
100+
nextStart = response.getNextStartPrimaryKey();
101+
}
102+
103+
return new Pair<List<Row>, RowPrimaryKey>(rows, nextStart);
104+
}
105+
106+
private static void readByPage(OTSClient client, String tableName) {
107+
int pageSize = 8;
108+
int offset = 33;
109+
110+
RowPrimaryKey startKey = new RowPrimaryKey();
111+
startKey.addPrimaryKeyColumn(COLUMN_GID_NAME, PrimaryKeyValue.INF_MIN);
112+
startKey.addPrimaryKeyColumn(COLUMN_UID_NAME, PrimaryKeyValue.INF_MIN);
113+
114+
RowPrimaryKey endKey = new RowPrimaryKey();
115+
endKey.addPrimaryKeyColumn(COLUMN_GID_NAME, PrimaryKeyValue.INF_MAX);
116+
endKey.addPrimaryKeyColumn(COLUMN_UID_NAME, PrimaryKeyValue.INF_MAX);
117+
// 读第一页,从范围的offset=33的行开始读起
118+
Pair<List<Row>, RowPrimaryKey> result = readByPage(client, tableName, startKey, endKey, offset, pageSize);
119+
for (Row row : result.getKey()) {
120+
System.out.println(row.getColumns());
121+
}
122+
System.out.println("Total rows count: " + result.getKey().size());
123+
124+
// 顺序翻页,读完范围内的所有数据
125+
startKey = result.getValue();
126+
while (startKey != null) {
127+
System.out.println("============= start read next page ==============");
128+
result = readByPage(client, tableName, startKey, endKey, 0, pageSize);
129+
for (Row row : result.getKey()) {
130+
System.out.println(row.getColumns());
131+
}
132+
startKey = result.getValue();
133+
System.out.println("Total rows count: " + result.getKey().size());
134+
}
135+
}
136+
137+
private static void createTable(OTSClient client, String tableName)
138+
throws ServiceException, ClientException {
139+
TableMeta tableMeta = new TableMeta(tableName);
140+
tableMeta.addPrimaryKeyColumn(COLUMN_GID_NAME, PrimaryKeyType.INTEGER);
141+
tableMeta.addPrimaryKeyColumn(COLUMN_UID_NAME, PrimaryKeyType.INTEGER);
142+
// 将该表的读写CU都设置为0
143+
CapacityUnit capacityUnit = new CapacityUnit(0, 0);
144+
145+
CreateTableRequest request = new CreateTableRequest();
146+
request.setTableMeta(tableMeta);
147+
request.setReservedThroughput(capacityUnit);
148+
client.createTable(request);
149+
150+
System.out.println("表已创建");
151+
}
152+
153+
private static void deleteTable(OTSClient client, String tableName)
154+
throws ServiceException, ClientException {
155+
DeleteTableRequest request = new DeleteTableRequest();
156+
request.setTableName(tableName);
157+
client.deleteTable(request);
158+
159+
System.out.println("表已删除");
160+
}
161+
162+
private static void putRows(OTSClient client, String tableName)
163+
throws OTSException, ClientException {
164+
int bid = 1;
165+
final int rowCount = 100;
166+
for (int i = 0; i < rowCount; ++i) {
167+
RowPutChange rowChange = new RowPutChange(tableName);
168+
RowPrimaryKey primaryKey = new RowPrimaryKey();
169+
primaryKey.addPrimaryKeyColumn(COLUMN_GID_NAME,
170+
PrimaryKeyValue.fromLong(bid));
171+
primaryKey.addPrimaryKeyColumn(COLUMN_UID_NAME,
172+
PrimaryKeyValue.fromLong(i));
173+
rowChange.setPrimaryKey(primaryKey);
174+
rowChange.addAttributeColumn(COLUMN_NAME_NAME,
175+
ColumnValue.fromString("小" + Integer.toString(i)));
176+
rowChange.addAttributeColumn(COLUMN_MOBILE_NAME,
177+
ColumnValue.fromString("111111111"));
178+
rowChange.addAttributeColumn(COLUMN_ADDRESS_NAME,
179+
ColumnValue.fromString("中国A地"));
180+
rowChange.addAttributeColumn(COLUMN_AGE_NAME,
181+
ColumnValue.fromLong(20));
182+
rowChange.setCondition(new Condition(
183+
RowExistenceExpectation.EXPECT_NOT_EXIST));
184+
185+
PutRowRequest request = new PutRowRequest();
186+
request.setRowChange(rowChange);
187+
188+
PutRowResult result = client.putRow(request);
189+
int consumedWriteCU = result.getConsumedCapacity()
190+
.getCapacityUnit().getWriteCapacityUnit();
191+
192+
System.out.println("成功插入数据, 消耗的写CU为:" + consumedWriteCU);
193+
}
194+
195+
System.out.println(String.format("成功插入%d行数据。", rowCount));
196+
}
197+
}

0 commit comments

Comments
 (0)