Spring Boot 集成 Phoenix + HBase

本文默认已安装好HBase1.4.7,不再介绍
Docker 安装HBase 并使用_羁客%的博客-CSDN博客
Windows 安装 HBase 单机_羁客%的博客-CSDN博客

一.安装python

apk add --no-cache python

二.下载|解压Phoenix

wget https://archive.apache.org/dist/phoenix/apache-phoenix-4.13.1-HBase-1.3/bin/apache-phoenix-4.13.1-HBase-1.3-bin.tar.gz
tar -xzvf apache-phoenix-4.13.1-HBase-1.3-bin.tar.gz
mv apache-phoenix-4.13.1-HBase-1.3-bin phoenix-4.13.1

三.复制jar包

cp phoenix-4.13.1-HBase-1.3-server.jar ../hbase/lib/

五.修改hbase-site.xml 配置文件

保持phoenix-4.13.1/bin/hbase-site.xml与hbase/conf/hbase-site.xml的一致,在hbase原有上新增映射设置

<property>
  <name>phoenix.schema.isNamespaceMappingEnabled</name>
   <value>true</value>
</property>
<property>
  <name>phoenix.schema.mapSystemTablesToNamespace</name>
  <value>true</value>
</property>

六.启动使用phoenix

1.启动

./sqlline.py

 2.创建|删除 命名空间

create schema IF NOT EXISTS "user";
drop schema "user";

3.使用命名空间

USE "user";

4.创建表

CREATE TABLE IF NOT EXISTS "student"(
  id VARCHAR NOT NULL primary key, 
  name VARCHAR,
  age VARCHAR,
  sex VARCHAR,
  date Date
);

5.插入测试数据

upsert into "student" (id,name,age,sex,date) values('1001','wangwu1','19','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1002','wangwu2','21','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1003','wangwu3','22','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1004','wangwu4','21','女','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1005','wangwu5','23','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1006','wangwu6','27','女','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1007','wangwu7','23','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1008','wangwu8','20','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1009','wangwu9','24','男','2023-9-18 22:50:15'); 

upsert into "student" (id,name,age,sex,date) values('1010','张三1','19','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1011','张三2','21','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1012','张三3','22','男','2023-9-18 22:50:15');
upsert into "student" (id,name,age,sex,date) values('1013','张三3','22','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1014','张三4','21','女','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1015','张三5','23','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1016','张三6','27','女','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1017','张三7','23','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1018','张三8','20','男','2023-9-18 22:50:15'); 
upsert into "student" (id,name,age,sex,date) values('1019','张三9','24','男','2023-9-18 22:50:15'); 

七.spring boot集成 使用phoenix 

1.引入依赖(版本与下载的phoenix保持一致,不然会连不上)

<!--phoenix core-->
<dependency>
    <groupId>org.apache.phoenix</groupId>
    <artifactId>phoenix-core</artifactId>
    <version>4.13.1-HBase-1.3</version>
    <exclusions>
        <exclusion>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>servlet-api-2.5</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>servlet-api-2.5-6.1.14</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!--管理protobuf-->
<dependencyManagement>
  <dependencies>
     <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java</artifactId>
        <version>2.5.0</version>
    </dependency>
  </dependencies>
</dependencyManagement>

2.在resources下创建hbase-site.xml文件

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>phoenix.schema.mapSystemTablesToNamespace</name>
        <value>true</value>
    </property>
    <property>
        <name>phoenix.schema.isNamespaceMappingEnabled</name>
        <value>true</value>
    </property>
</configuration>

3.配置application.yml

spring:
  #数据源
  datasource:
    phoenix:
      driverClassName: org.apache.phoenix.jdbc.PhoenixDriver
      jdbcUrl: jdbc:phoenix:127.0.0.1:2381
      type: com.zaxxer.hikari.HikariDataSource
      initialSize: 10
      maxActive: 20
      minIdle: 1
      maximumPoolSize: 20
      autoCommit: true
      poolName: HikariPool_phoenix
      connectionTestQuery: SELECT 1

4.配置hikairi连接池

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.xxx.xxx.mapper", sqlSessionFactoryRef = "phoenixSessionFactory")
public class HikariPhoenixConfig {

    /**
     * @ConfigurationProperties 读取yml中的配置参数映射成为一个对象
     */
    @Bean(name = "phoenixDateSource")
    @ConfigurationProperties(prefix = "spring.datasource.phoenix")
    public HikariDataSource phoenixDateSource() {
        return new HikariDataSource();
    }

    @Bean(name = "phoenixSessionFactory")
    public SqlSessionFactory phoenixSessionFactory(@Qualifier("phoenixDateSource") DataSource datasource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);

        //-----单路径是扫描
        //mybatis扫描xml所在位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/phoenix/*.xml"));
        return bean.getObject();
    }

    @Bean("phoenixSessionTemplate")
    public SqlSessionTemplate phoenixSessionTemplate(@Qualifier("phoenixSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

5.在spring boot中使用phoenix

(1).controller

import cn.dev33.satoken.util.SaResult;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;


@RequiredArgsConstructor
@RestController
@RequestMapping("/hbase/student")
public class StudentController {

    private final StudentService studentService;

    /**
     * 根据开始、结束行
     *
     * @param pageNumber 当前页
     * @param pageSize   每页显示条数
     * @return 结果
     */
    @RequestMapping("/list")
    public SaResult list(@Param("pageNumber") Integer pageNumber, @Param("pageSize") Integer pageSize) {
        PageInfo<Student> list = studentService.selectList(pageNumber, pageSize);
        return SaResult.data(list);
    }

    /**
     * 根据开始、结束行
     *
     * @param student 参数对象
     * @return 结果
     */
    @PostMapping("/saveOrUpdate")
    public SaResult saveOrUpdate(@RequestBody Student student) {
        studentService.saveOrUpdate(student);
        return SaResult.ok("保存成功!");
    }

    /**
     * 根据开始、结束行
     *
     * @param id id
     * @return 结果
     */
    @GetMapping("/delete")
    public SaResult delete(@RequestParam("id") String id) {
        studentService.delete(id);
        return SaResult.ok("保存成功!");
    }
} 

(2).service

import com.github.pagehelper.PageInfo;


public interface StudentService {

    /**
     * 根据开始、结束行
     *
     * @param pageNumber 当前页
     * @param pageSize   每页显示条数
     * @return 结果
     */
    PageInfo<Student> selectList(Integer pageNumber, Integer pageSize);

    /**
     * 根据开始、结束行
     *
     * @param student 参数对象
     */
    void saveOrUpdate(Student student);

    /**
     * 根据开始、结束行
     *
     * @param id id
     */
    void delete(String id);
}


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gyrw.stock.hbase.mapper.StudentMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *
 * </p >
 *
 * @version: V1.0.0
 */
@RequiredArgsConstructor
@Service
public class StudentServiceImpl implements StudentService {

    private final StudentMapper studentMapper;

    /**
     * 根据开始、结束行
     *
     * @param pageNumber 当前页
     * @param pageSize   每页显示条数
     * @return pageInfo
     */
    @Override
    public PageInfo<Student> selectList(Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<Student> students = studentMapper.queryAll();
        return new PageInfo<>(students);
    }

    /**
     * 根据开始、结束行
     *
     * @param student 参数对象
     */
    @Override
    public void saveOrUpdate(Student student) {
        //查询最大的ID值
        Student studentVo = studentMapper.selectMax();
        if (ObjectUtils.isEmpty(studentVo)) {
            student.setId("1001");
        } else if (!StringUtils.hasLength(student.getId())) {
            student.setId(String.valueOf(Long.parseLong(studentVo.getId()) + 1));
        }
        student.setDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        studentMapper.saveOrUpdate(student);
    }

    /**
     * 根据开始、结束行
     *
     * @param id id
     */
    @Override
    public void delete(String id) {
        studentMapper.delete(id);
    }
}

(3).mapper

import com.gyrw.stock.hbase.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 学生的 mapper
 * </p >
 *
 * @copyright: Copyright (c) 2023
 * @version: V1.0.0
 */

public interface StudentMapper {

    @Select("SELECT * from \"user\".\"student\"")
    List<Student> queryAll();

    @Select("select * from \"user\".\"student\" order by id desc limit 1")
    Student selectMax();

    @Insert("upsert into \"user\".\"student\" VALUES(#{id},#{name},#{sex},#{age},#{date})")
    void saveOrUpdate(Student student);

    @Delete("DELETE FROM \"user\".\"student\" WHERE id = #{id}")
    void delete(@Param("id") String id);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Flume、Kafka和HBase都是大数据领域常用的组件,它们可以很好地协同工作来实现数据的实时采集、传输和存储。下面是它们的集成配置。 1. 安装Flume Flume是Apache基金会下的分布式、可靠、高可用的海量日志采集、聚合和传输系统。它支持多种数据源和数据目的地,可以将多种数据源的数据采集到Hadoop平台中进行处理和分析。 安装Flume的步骤如下: - 下载Flume并解压缩 - 配置Flume环境变量 - 配置Flume代理 2. 安装Kafka Kafka是由Apache软件基金会开发的一个开源流处理平台,它是一种高吞吐量的分布式发布-订阅消息系统,适用于大规模的数据流处理。 安装Kafka的步骤如下: - 下载Kafka并解压缩 - 配置Kafka环境变量 - 配置Kafka服务端 3. 安装HBase HBase是一个分布式、可扩展、高可用的NoSQL数据库,它是Hadoop生态圈中的一员,可以处理大规模的结构化和半结构化数据。 安装HBase的步骤如下: - 下载HBase并解压缩 - 配置HBase环境变量 - 配置HBase服务端 4. 配置Flume采集数据 Flume支持多种数据源和数据目的地,可以根据不同的需求进行配置。在此我们以采集日志为例,配置Flume将采集到的日志数据发送到Kafka。 Flume的配置文件如下: ```properties # Name the components on this agent agent.sources = r1 agent.sinks = k1 agent.channels = c1 # Describe/configure the source agent.sources.r1.type = exec agent.sources.r1.command = tail -F /data/logs/access.log agent.sources.r1.batchSize = 1000 agent.sources.r1.batchDurationMillis = 2000 # Describe the sink agent.sinks.k1.type = org.apache.flume.sink.kafka.KafkaSink agent.sinks.k1.brokerList = localhost:9092 agent.sinks.k1.topic = access_log # Use a channel which buffers events in memory agent.channels.c1.type = memory agent.channels.c1.capacity = 10000 agent.channels.c1.transactionCapacity = 1000 # Bind the source and sink to the channel agent.sources.r1.channels = c1 agent.sinks.k1.channel = c1 ``` 5. 配置Kafka接收数据 Kafka支持多个topic,多个partition,可以根据需求进行配置。在此我们以接收Flume发送的数据为例,创建一个名为access_log的topic,并将接收到的数据存储到HBase中。 Kafka的配置文件如下: ```properties # Broker configuration broker.id=0 listeners=PLAINTEXT://localhost:9092 num.network.threads=3 num.io.threads=8 socket.send.buffer.bytes=102400 socket.receive.buffer.bytes=102400 socket.request.max.bytes=104857600 # Topic configuration num.partitions=1 offsets.topic.replication.factor=1 transaction.state.log.replication.factor=1 transaction.state.log.min.isr=1 # Zookeeper configuration zookeeper.connect=localhost:2181 zookeeper.connection.timeout.ms=6000 # HBase configuration hbase.zookeeper.quorum=localhost hbase.zookeeper.property.clientPort=2181 hbase.cluster.distributed=true hbase.rootdir=hdfs://localhost:9000/hbase ``` 6. 配置HBase存储数据 HBase支持多个表,多个列族,可以根据需求进行配置。在此我们以存储access_log为例,创建一个名为access_log的表,并在其中创建一个名为cf的列族。 HBase的配置文件如下: ```xml <configuration> <property> <name>hbase.rootdir</name> <value>hdfs://localhost:9000/hbase</value> </property> <property> <name>hbase.zookeeper.quorum</name> <value>localhost</value> </property> <property> <name>hbase.zookeeper.property.clientPort</name> <value>2181</value> </property> </configuration> ``` 7. 启动服务 按照以下顺序启动服务: - 启动Zookeeper服务 - 启动Kafka服务 - 启动HBase服务 - 启动Flume服务 启动命令如下: ```bash # 启动Zookeeper服务 bin/zookeeper-server-start.sh config/zookeeper.properties # 启动Kafka服务 bin/kafka-server-start.sh config/server.properties # 启动HBase服务 bin/start-hbase.sh # 启动Flume服务 bin/flume-ng agent -n agent -c conf -f conf/flume.conf -Dflume.root.logger=INFO,console ``` 8. 验证数据 启动服务后,Flume将会采集到access.log的数据并发送到Kafka中,Kafka将会接收到数据并将其存储到HBase中。可以通过HBase命令行或Web界面来查看数据是否已经存储。 HBase命令行: ```bash # 进入HBase shell bin/hbase shell # 创建表 create 'access_log', 'cf' # 查看表 list # 插入数据 put 'access_log', 'row1', 'cf:col1', 'value1' # 查看数据 scan 'access_log' ``` HBase Web界面: 在浏览器中输入http://localhost:16010,可以进入HBase Web界面,可以通过该界面来查看表、列族、数据等信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值