TableStore+java:建立SyncClient+getRow读取一行数据

一、经过控制台或者客户端,在TableStore中新建了实例owlforest,在实例详情中获取到实例访问地址endPoint web

二、新建表user,肯定主键为userid(Interger)类型,由于TableStore最多支持4个主键,这里先尝试一个主键的状况。spring

三、经过控制台新增数据 app

四、修改pom.xmlsocket

<dependency>
    <groupId>com.aliyun.openservices</groupId>
    <artifactId>tablestore</artifactId>
    <version>4.10.2</version>
</dependency>

五、经过主键,用getRow获取一行数据(使用默认配置建立 SyncClient)ui

import com.alicloud.openservices.tablestore.SyncClient;
import com.alicloud.openservices.tablestore.model.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Tablestore {
    final String endPoint = "实例访问地址";
    final String accessKeyId = "accessKeyId";
    final String accessKeySecret = "accessKeySecret";
    final String instanceName = "实例名";
    @RequestMapping("/query")
    public String query() {
        SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName);
        GetRowRequest rowRequest = new GetRowRequest();
        SingleRowQueryCriteria queryCriteria = new SingleRowQueryCriteria("user");
        //读取数据时,返回的最多版本个数。
        queryCriteria.setMaxVersions(5);
        //主键
        PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
        primaryKeyBuilder.addPrimaryKeyColumn("userid", PrimaryKeyValue.fromLong(2));
        queryCriteria.setPrimaryKey(primaryKeyBuilder.build());
        rowRequest.setRowQueryCriteria(queryCriteria);
        GetRowResponse rowResponse = client.getRow(rowRequest);
        if(rowResponse == null){
            return "未获取到TableStore的数据";
        }else{
            String responseMsg = "";
            Column[] cols = rowResponse.getRow().getColumns();
            for (Column col : cols){
                System.out.println(col.getName());
                System.out.println(col.getValue());
                responseMsg = responseMsg + "Name:" + col.getName() + ",Value:" + col.getValue() + ", ";
            }
            return responseMsg;
        }
    }
}

采用自定义配置的方式建立SyncClientrest

ClientConfiguration clientConfiguration = new ClientConfiguration();
// 设置创建链接的超时时间。
clientConfiguration.setConnectionTimeoutInMillisecond(5000);
// 设置socket超时时间。
clientConfiguration.setSocketTimeoutInMillisecond(5000);
// 设置重试策略,若不设置,采用默认的重试策略。
clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy());
// 其余配置项省略
SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName, clientConfiguration);

六、结果code

相关文章
相关标签/搜索