【发布时间】:2022-02-04 23:59:58
【问题描述】:
我正在尝试使用 cassandra 作为数据库构建 REST API,但我没有看到任何在线文档或示例,我正在使用 datastax java 驱动程序 3.0.0。
public class CassandraDBUtil {
private Cluster cluster;
private PoolingOptions options;
private Session session;
public void connect(String node) {
options = new PoolingOptions(). setMaxRequestsPerConnection(HostDistance.LOCAL, 32768);
cluster = Cluster.builder()
.addContactPoint(node)
.withAddressTranslator(new EC2MultiRegionAddressTranslator())
.withPoolingOptions(options)
.build();
Metadata metadata = cluster.getMetadata();
System.out.printf("Connected to cluster: %s\n", metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n", host.getDatacenter(), host.getAddress(),
host.getRack());
}
session = cluster.connect("dropalletcassdb");
}
public Session getSession(){
if(this.cluster != null){
System.out.println("@@@@ Returning an old session");
return this.session;
}else{
System.out.println("@@@ Creating a new session");
connect("127.0.0.1");
return this.session;
}
}
下面是另一个类的函数,
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public List<ActiveBid> getTrackInJSON() {
logger.info("LoginApi: Returning the active bid");
Session session = cassDB.getSession();
String cqlStatement = "select * from active_bid where username='xyz'";
for (Row row : session.execute(cqlStatement)) {
System.out.println(row.toString());
}
session.close();
ActiveBid activeBid = new ActiveBid("3d673111-894d-4fcb-84f7-7d027a9a2419", "XXX-XXX-XXXXXXX", "/p/project_id=1367777", 25, new BigInteger("125"), new BigInteger("150"), "2016-06-04 18:32:37");
List<ActiveBid> activeBidList = new ArrayList<ActiveBid>();
activeBidList.add(activeBid);
return activeBidList;
}
在上面的代码中,我有构建集群和会话的 util 类,然后我在另一个类中有 getTrackInJSON,当向http://localhost:8080/cassExample/rest/get 发出请求时,它会被调用。每次我调用 /get 时,它都会构建集群和会话,平均响应时间为 500 毫秒。我不确定我做错了什么,我什至没有将结果集作为响应返回,我正在返回一个模拟的响应并且它花费了很多时间。有人能指出我正确的方向吗?
【问题讨论】: