TableStore:读取数据getRow

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

2、新建表user,确定主键为userid(Interger)类型,因为TableStore最多支持4个主键,这里先尝试一个主键的情况。

3、通过控制台新增一行数据

4、修改pom.xml

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

5、通过主键,用getRow获取一行数据

package com.aliyun.demo.controller;

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 = "这里填写子账户的KeyId,详情参照阿里云文档";
    final String accessKeySecret = "这里填写子账户的Keyecret,详情参照阿里云文档";
    final String instanceName = "owlforest"; //实例名

    @RequestMapping("/query")
    public String query() {
        /*// ClientConfiguration提供了很多配置项,以下只列举部分。
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        // 设置建立连接的超时时间。
        clientConfiguration.setConnectionTimeoutInMillisecond(5000);
        // 设置socket超时时间。
        clientConfiguration.setSocketTimeoutInMillisecond(5000);
        // 设置重试策略,若不设置,采用默认的重试策略。
        clientConfiguration.setRetryStrategy(new AlwaysRetryStrategy());
        SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName, clientConfiguration);*/

        SyncClient client = new SyncClient(endPoint, accessKeyId, accessKeySecret, instanceName);
        GetRowRequest rowRequest = new GetRowRequest();

        //参数是表名
        SingleRowQueryCriteria queryCriteria = new SingleRowQueryCriteria("user");
        //读取数据时,返回的最多版本个数。
        queryCriteria.setMaxVersions(5);
        //主键
        PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
        //这里要用PrimaryKeyValue.fromLong,因为主键是Integer类型,如果写成fromString是要报错的
        primaryKeyBuilder.addPrimaryKeyColumn("userid", PrimaryKeyValue.fromLong(1));
        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());
            }
            return "有数据!";
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/wsfu/p/10527452.html