项目正好在做,刚好完成这个小功能,所以记录下:
材料准备:
- Spring Boot项目
- hadoop集群(伪分布式都可以)
- hive
步骤:
- 在Spring Boot项目 pom中引入所需依赖:
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>${hive.version}</version>
</dependency>
- 确保开启了hive对应服务
# 开启hiveserver2服务
${HIVE_HOME}/bin/hiveserver2
# 开启metastore服务
${HIVE_HOME}/bin/hive --service metastore
- 在service层连接hive,执行查询并返回结果
import com.tencent.udpdlake.dataqualitycheck.service.HiveTestService;
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
@Service
public class HiveTestServiceImpl implements HiveTestService {
@Override
public String query() throws Exception {
Class.forName("org.apache.hive.jdbc.HiveDriver");
// String url = "jdbc:hive2://host:10000/default";
//高可用方式:客户端选择可用的hiveserver
String url = "jdbc:hive2://vm01:10000/default";
Connection conn = DriverManager.getConnection(url, "root", "123456");
Statement st = conn.createStatement();
String sqlString = "SHOW DATABASES";
StringBuilder sb = new StringBuilder();
ResultSet rs = st.executeQuery(sqlString);
while (rs.next()) {
sb.append(rs.getString(1)).append("-");
}
rs.close();
st.close();
conn.close();
return sb.toString();
}
}
- 在Controller中调用Service,并返回结果到前端
import com.service.HiveTestService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping(value = "/")
public class HiveTestController {
@Resource
private HiveTestService hiveTestService;
@GetMapping(value = "")
public String test() throws Exception {
return hiveTestService.query();
}
}
- 浏览器访问,这里的路由为:localhost:8080