HbaseTemplate.saveOrUpdates 保存或者更新如果 HbaseTemplate 操作不满足需求,完全可以使用 hbaseTemplate 的getConnection() 方法,获取连接。进而类似 HbaseTemplate 实现的逻辑,实现更复杂的需求查询等功能
@Service
public class CityServiceImpl implements CityService {
@Autowired private HbaseTemplate hbaseTemplate;
//查询
public List query(String startRow, String stopRow) {
Scan scan = new Scan(Bytes.toBytes(startRow), Bytes.toBytes(stopRow));
scan.setCaching(5000);
List dtos = this.hbaseTemplate.find("people_table", scan, new CityRowMapper());
return dtos;
}
//查询
public City query(String row) {
City dto = this.hbaseTemplate.get("people_table", row, new CityRowMapper());
return dto;
}
//新增或者更新
public void saveOrUpdate() {
List saveOrUpdates = new ArrayList();
Put put = new Put(Bytes.toBytes("135xxxxxx"));
put.addColumn(Bytes.toBytes("people"), Bytes.toBytes("name"), Bytes.toBytes("test"));
saveOrUpdates.add(put);
this.hbaseTemplate.saveOrUpdates("people_table", saveOrUpdates);
}
}
Springboot整合Influxdb
中文文档:https://jasper-zhang1.gitbooks.io/influxdb/content/Introduction/installation.html
注意,项目建立在spring-boot-web基础上
1、添加依赖
org.influxdb
influxdb-java
2.15
2、添加配置
spring:
influx:
database: my_sensor1
password: admin
url: http://127.0.0.1:6086
user: admin
3、编写配置类
@Configuration
public class InfluxdbConfig {
@Value("${spring.influx.url}")
private String influxDBUrl;
@Value("${spring.influx.user}")
private String userName;
@Value("${spring.influx.password}")
private String password;
@Value("${spring.influx.database}")
private String database;
@Bean("influxDB")
public InfluxDB influxdb(){
InfluxDB influxDB = InfluxDBFactory.connect(influxDBUrl, userName, password);
try {
/**
* 异步插入:
* enableBatch这里第一个是point的个数,第二个是时间,单位毫秒
* point的个数和时间是联合使用的,如果满100条或者60 * 1000毫秒
* 满足任何一个条件 就会发送一次写的请求。
*/
influxDB.setDatabase(database).enableBatch(100,1000 * 60, TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
} finally {
//设置默认策略
influxDB.setRetentionPolicy("sensor_retention");
}
//设置日志输出级别
influxDB.setLogLevel(InfluxDB.LogLevel.BASIC);
return influxDB;
}
}
4、InfluxDB原生API实现
@SpringBootTest(classes = {MainApplication.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class InfluxdbDBTest {
@Autowired
private InfluxDB influxDB;
//measurement
private final String measurement = "sensor";
@Value("${spring.influx.database}")
private String database;
/**
* 批量插入第一种方式
*/
@Test
public void insert(){
List lines = new ArrayList();
Point point = null;
for(int i=0;i<50;i++){
point = Point.measurement(measurement)
.tag("deviceId", "sensor" + i)
.addField("temp", 3)
.addField("voltage", 145+i)
.addField("A1", "4i")
.addField("A2", "4i").build();
lines.add(point.lineProtocol());
}
//写入
influxDB.write(lines);
}
/**
* 批量插入第二种方式
*/
@Test
public void batchInsert(){
BatchPoints batchPoints = BatchPoints
.database(database)
.consistency(InfluxDB.ConsistencyLevel.ALL)
.build();
//遍历sqlserver获取数据
for(int i=0;i<50;i++){
//创建单条数据对象——表名
Point point = Point.measurement(measurement)
//tag属性——只能存储String类型
.tag("deviceId", "sensor" + i)
.addField("temp", 3)
.addField("voltage", 145+i)
.addField("A1", "4i")
.addField("A2", "4i").build();
//将单条数据存储到集合中
batchPoints.point(point);
}
//批量插入
influxDB.write(batchPoints);
}
/**
* 获取数据
*/
@Test
public void datas(@RequestParam Integer page){
int pageSize = 10;
// InfluxDB支持分页 查询,因此可以设置分页查询条件
String pageQuery = " LIMIT " + pageSize + " OFFSET " + (page - 1) * pageSize;
String queryCondition = ""; //查询条件暂且为空
// 此处查询所有内容,如果
String queryCmd = "SELECT * FROM "
// 查询指定设备下的日志信息
// 要指定从 RetentionPolicyName.measurement中查询指定数据,默认的策略可以不加;
// + 策略name + "." + measurement
+ measurement
// 添加查询条件(注意查询条件选择tag值,选择field数值会严重拖慢查询速度)
+ queryCondition
// 查询结果需要按照时间排序
+ " ORDER BY time DESC"
// 添加分页查询条件
+ pageQuery;
QueryResult queryResult = influxDB.query(new Query(queryCmd, database));
System.out.println("query result => "+queryResult);
}
}
5、采用封装工具类
1、创建实体类
@Data
@Measurement(name = "sensor")
public class Sensor {
@Column(name="deviceId",tag=true)
private String deviceId;
@Column(name="temp")
private float temp;
@Column(name="voltage")
private float voltage;
@Column(name="A1")
private float A1;
@Column(name="A2")
private float A2;
@Column(name="time")
private String time;
}
2、创建工具类
@Component
public class InfluxdbUtils {
@Autowired
private InfluxDB influxDB;
@Value("${spring.influx.database}")
private String database;
/**
* 新增单条记录,利用java的反射机制进行新增操作
*/
@SneakyThrows
public void insertOne(Object obj){
//获取度量
Class> clasz = obj.getClass();
Measurement measurement = clasz.getAnnotation(Measurement.class);
//构建
Point.Builder builder = Point.measurement(measurement.name());
// 获取对象属性
Field[] fieldArray = clasz.getDeclaredFields();
Column column = null;
for(Field field : fieldArray){
column = field.getAnnotation(Column.class);
//设置属性可操作
field.setAccessible(true);
if(column.tag()){
//tag属性只能存储String类型
builder.tag(column.name(), field.get(obj).toString());
}else{
//设置field
if(field.get(obj) != null){
builder.addField(column.name(), field.get(obj).toString());
}
}
}
influxDB.write(builder.build());
}
/**
* 批量新增,方法一
*/
@SneakyThrows
public void insertBatchByRecords(List> records){
List lines = new ArrayList();
records.forEach(record->{
Class> clasz = record.getClass();
//获取度量
Measurement measurement = clasz.getAnnotation(Measurement.class);
//构建
Point.Builder builder = Point.measurement(measurement.name());
Field[] fieldArray = clasz.getDeclaredFields();
Column column = null;
for(Field field : fieldArray){
column = field.getAnnotation(Column.class);
//设置属性可操作
field.setAccessible(true);
if(column.tag()){
//tag属性只能存储String类型
builder.tag(column.name(), field.get(record).toString());
}else{
//设置field
if(field.get(record) != null){
builder.addField(column.name(), field.get(record).toString());
}
}
}
lines.add(builder.build().lineProtocol());
});
influxDB.write(lines);
}
/**
* 批量新增,方法二
*/
@SneakyThrows
public void insertBatchByPoints(List> records){
BatchPoints batchPoints = BatchPoints.database(database)
.consistency(InfluxDB.ConsistencyLevel.ALL)
.build();
records.forEach(record->{
Class> clasz = record.getClass();
//获取度量
Measurement measurement = clasz.getAnnotation(Measurement.class);
//构建
Point.Builder builder = Point.measurement(measurement.name());
Field[] fieldArray = clasz.getDeclaredFields();
Column column = null;
for(Field field : fieldArray){
column = field.getAnnotation(Column.class);
//设置属性可操作
field.setAccessible(true);
if(column.tag()){
//tag属性只能存储String类型
builder.tag(column.name(), field.get(record).toString());
}else{
//设置field
if(field.get(record) != null){
builder.addField(column.name(), field.get(record).toString());
}
}
}
batchPoints.point(builder.build());
});
influxDB.write(batchPoints);
}
/**
* 查询,返回Map集合
* @param query 完整的查询语句
*/
public List fetchRecords(String query){
List results = new ArrayList();
QueryResult queryResult = influxDB.query(new Query(query, database));
queryResult.getResults().forEach(result->{
result.getSeries().forEach(serial->{
List columns = serial.getColumns();
int fieldSize = columns.size();
serial.getValues().forEach(value->{
Map obj = new HashMap();
for(int i=0;i
obj.put(columns.get(i), value.get(i));
}
results.add(obj);
});
});
});
return results;
}
/**
* 查询,返回map集合
* @param fieldKeys 查询的字段,不可为空;不可为单独的tag
* @param measurement 度量,不可为空;
*/
public List fetchRecords(String fieldKeys, String measurement){
StringBuilder query = new StringBuilder();
query.append("select ").append(fieldKeys).append(" from ").append(measurement);
return this.fetchRecords(query.toString());
}
/**
* 查询,返回map集合
* @param fieldKeys 查询的字段,不可为空;不可为单独的tag
* @param measurement 度量,不可为空;
*/
public List fetchRecords(String fieldKeys, String measurement, String order){
StringBuilder query = new StringBuilder();
query.append("select ").append(fieldKeys).append(" from ").append(measurement);
query.append(" order by ").append(order);
return this.fetchRecords(query.toString());
}
/**
* 查询,返回map集合
* @param fieldKeys 查询的字段,不可为空;不可为单独的tag
* @param measurement 度量,不可为空;
*/
public List fetchRecords(String fieldKeys, String measurement, String order, String limit){
StringBuilder query = new StringBuilder();
query.append("select ").append(fieldKeys).append(" from ").append(measurement);
query.append(" order by ").append(order);
query.append(limit);
return this.fetchRecords(query.toString());
}
/**
* 查询,返回对象的list集合
*/
@SneakyThrows
public List fetchResults(String query, Class> clasz){
List results = new ArrayList<>();
QueryResult queryResult = influxDB.query(new Query(query, database));
queryResult.getResults().forEach(result->{
result.getSeries().forEach(serial->{
List columns = serial.getColumns();
int fieldSize = columns.size();
serial.getValues().forEach(value->{
Object obj = null;
obj = clasz.newInstance();
for(int i=0;i
String fieldName = columns.get(i);
Field field = clasz.getDeclaredField(fieldName);
field.setAccessible(true);
Class> type = field.getType();
if(type == float.class){
field.set(obj, Float.valueOf(value.get(i).toString()));
}else{
field.set(obj, value.get(i));
}
}
results.add(obj);
});
});
});
return results;
}
/**
* 查询,返回对象的list集合
*/
public List fetchResults(String fieldKeys, String measurement, Class> clasz){
StringBuilder query = new StringBuilder();
query.append("select ").append(fieldKeys).append(" from ").append(measurement);
return this.fetchResults(query.toString(), clasz);
}
/**
* 查询,返回对象的list集合
*/
public List fetchResults(String fieldKeys, String measurement, String order, Class> clasz){
StringBuilder query = new StringBuilder();
query.append("select ").append(fieldKeys).append(" from ").append(measurement);
query.append(" order by ").append(order);
return this.fetchResults(query.toString(), clasz);
}
/**
* 查询,返回对象的list集合
*/
public List fetchResults(String fieldKeys, String measurement, String order, String limit, Class> clasz){
StringBuilder query = new StringBuilder();
query.append("select ").append(fieldKeys).append(" from ").append(measurement);
query.append(" order by ").append(order);
query.append(limit);
return this.fetchResults(query.toString(), clasz);
}
}
3、使用工具类的测试代码
@SpringBootTest(classes = {MainApplication.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class InfluxdbUtilTest {
@Autowired
private InfluxdbUtils influxdbUtils;
/**
* 插入单条记录
*/
@Test
public void insert(){
Sensor sensor = new Sensor();
sensor.setA1(10);
sensor.setA2(10);
sensor.setDeviceId("0002");
sensor.setTemp(10L);
sensor.setTime("2021-01-19");
sensor.setVoltage(10);
influxdbUtils.insertOne(sensor);
}
/**
* 批量插入第一种方式
*/
@GetMapping("/index22")
public void batchInsert(){
List sensorList = new ArrayList();
for(int i=0; i<50; i++){
Sensor sensor = new Sensor();
sensor.setA1(2);
sensor.setA2(12);
sensor.setTemp(9);
sensor.setVoltage(12);
sensor.setDeviceId("sensor4545-"+i);
sensorList.add(sensor);
}
influxdbUtils.insertBatchByRecords(sensorList);
}
/**
* 批量插入第二种方式
*/
@GetMapping("/index23")
public void batchInsert1(){
List sensorList = new ArrayList();
Sensor sensor = null;
for(int i=0; i<50; i++){
sensor = new Sensor();
sensor.setA1(2);
sensor.setA2(12);
sensor.setTemp(9);
sensor.setVoltage(12);
sensor.setDeviceId("sensor4545-"+i);
sensorList.add(sensor);
}
influxdbUtils.insertBatchByPoints(sensorList);
}
/**
* 查询数据
*/
@GetMapping("/datas2")
public void datas(@RequestParam Integer page){
int pageSize = 10;
// InfluxDB支持分页查询,因此可以设置分页查询条件
String pageQuery = " LIMIT " + pageSize + " OFFSET " + (page - 1) * pageSize;
String queryCondition = ""; //查询条件暂且为空
// 此处查询所有内容,如果
String queryCmd = "SELECT * FROM sensor"
// 查询指定设备下的日志信息
// 要指定从 RetentionPolicyName.measurement中查询指定数据,默认的策略可以不加;
// + 策略name + "." + measurement
// 添加查询条件(注意查询条件选择tag值,选择field数值会严重拖慢查询速度)
+ queryCondition
// 查询结果需要按照时间排序
+ " ORDER BY time DESC"
// 添加分页查询条件
+ pageQuery;
List sensorList = influxdbUtils.fetchRecords(queryCmd);
System.out.println("query result => {}"+sensorList );
}
/**
* 获取数据
*/
@GetMapping("/datas21")
public void datas1(@RequestParam Integer page){
int pageSize = 10;
// InfluxDB支持分页查询,因此可以设置分页查询条件
String pageQuery = " LIMIT " + pageSize + " OFFSET " + (page - 1) * pageSize;
String queryCondition = ""; //查询条件暂且为空
// 此处查询所有内容,如果
String queryCmd = "SELECT * FROM sensor"
// 查询指定设备下的日志信息
// 要指定从 RetentionPolicyName.measurement中查询指定数据,默认的策略可以不加;
// + 策略name + "." + measurement
// 添加查询条件(注意查询条件选择tag值,选择field数值会严重拖慢查询速度)
+ queryCondition
// 查询结果需要按照时间排序
+ " ORDER BY time DESC"
// 添加分页查询条件
+ pageQuery;
List sensorList = influxdbUtils.fetchResults(queryCmd, Sensor.class);
//List sensorList = influxdbUtils.fetchResults("*", "sensor", Sensor.class);
sensorList.forEach(sensor->{
System.out.println("query result => {}"+sensorList );
});
}
}
6、采用封装数据模型的方式
1、在Influxdb库中创建存储策略
CREATE RETENTION POLICY "rp_order_payment" ON "db_order" DURATION 30d REPLICATION 1 DEFAULT
2、创建数据模型
@Data
@Measurement(name = "m_order_payment",
database = "db_order",
retentionPolicy = "rp_order_payment")
public class OrderPayment implements Serializable {
// 统计批次
@Column(name = "batch_id", tag = true)
private String batchId;
// 哪个BU
@Column(name = "bu_id", tag = true)
private String buId;
// BU 名称
@Column(name = "bu_name")
private String buName;
// 总数
@Column(name = "total_count", tag = true)
private String totalCount;
// 支付量
@Column(name = "pay_count", tag = true)
private String payCount;
// 金额
@Column(name = "total_money", tag = true)
private String totalMoney;
}
3、创建Mapper
public class InfluxMapper extends InfluxDBMapper {
public InfluxMapper(InfluxDB influxDB) {
super(influxDB);
}
}
4、配置Mapper
@Log4j2
@Configuration
public class InfluxAutoConfiguration {
@Bean
public InfluxMapper influxMapper(InfluxDB influxDB) {
InfluxMapper influxMapper = new InfluxMapper(influxDB);
return influxMapper;
}
}
5、测试CRUD
@SpringBootTest(classes = {MainApplication.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class InfluxdbMapperTest {
@Autowired
private InfluxMapper influxMapper;
@Test
public void save(OrderPayment product) {
influxMapper.save(product);
}
@Test
public void queryAll() {
List products = influxMapper.query(OrderPayment.class);
System.out.println(products);
}
@Test
public void queryByBu(String bu) {
String sql = String.format("%s'%s'", "select * from m_order_payment where bu_id = ", bu);
Query query = new Query(sql, "db_order");
List products = influxMapper.query(query, OrderPayment.class);
System.out.println(products);
}
}
参考:https://blog.csdn.net/cpongo1/article/details/89550486
https://github.com/SpringForAll/spring-boot-starter-hbase
https://github.com/JeffLi1993/springboot-learning-example