SpringBoot - 实现基于Elasticsearch+HBase全文检索系统教程2(数据采集及存储)
作者:hangge | 2025-05-30 08:38
四、数据采集及存储
1,数据说明
(1)这里我们使用极速数据提供的新闻 API 接口来获取数据,接口地址如下:
https://api.jisuapi.com/news/get?channel=头条&start=0&num=40&appkey=b98bce57191c076a
(2)返回的数据为如下 JSON 格式:

2,代码实现
(1)为方便操作 HBase,我们首先创建一个 HBaseUtils 工具类,具体可以参考我之前写的文章:
(2)下面代码我们通过接口获取新闻数据,然后将数据入库保存到 HBase 中,同时将 Rowkey 保存到 Redis 中。
@RestController
public class TestController {
@Autowired
private HBaseUtils hbaseUtils;
@Autowired
StringRedisTemplate stringRedisTemplate; //默认提供的用来操作字符串的redis操作实例
@GetMapping("/load")
public void load() {
// 通过接口获取新闻数据
String apiUrl = "https://api.jisuapi.com/news/get?channel=头条" +
"&start=0&num=40&appkey=b98bce57191c076a";
RestTemplate restTemplate = new RestTemplate();
String jsonResponse = restTemplate.getForObject(apiUrl, String.class);
JSONObject jsonObject = JSON.parseObject(jsonResponse);
JSONArray resList = jsonObject.getJSONObject("result").getJSONArray("list");
System.out.println("获取文章数:" + resList.size());
// 遍历数据
for(int i = 0; i < resList.size(); i++) {
JSONObject item = resList.getJSONObject(i);
//生成唯一的UUID作为HBase的Rowkey和ES的ID
String id= UUID.randomUUID().toString();
String title =item.getString("title");
String src = item.getString("src");
String content = item.getString("content");
String time = item.getString("time");
// 将数据入库HBase
String tableName = "article";
String cf = "info";
hbaseUtils.putData(tableName, id, cf,
Arrays.asList("title", "src", "content", "time"),
Arrays.asList(title, src, content, time));
// 将Rowkey保存到Redis中
stringRedisTemplate.opsForList().leftPush("l_article_ids", id);
}
}
}
3,运行测试
(1)首先执行如下命令启动 HBase 的 shell 命令行工具:
./bin/hbase shell
(2)接着执行如下命令在 HBase 中创建表 article:
create 'article','info'
(3)我们启动项目,然后访问项目的 /load 接口开始采集并保存数据:

(4)然后在 HBase 中验证数据是否都导入:
count 'article'
- 使用 scan 'article' 命令可以查看详细数据:

(5)同时查看 Redis 中所有的 id 数据是否都导入了:

全部评论(0)