微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java连接hbase、redis、mysql

很多时候突然要写一个连接的时候,还要去找度娘,特意整理下,要求自己时不时来看看。

hbase连接

package com.lagou.hbase.client;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class HbaseClientDemo {
    Configuration conf = null;
    Connection conn = null;

    @Before
    public void init() throws IOException {
        //获取一个配置文件对象
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "linux1,linux2,linux3");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        //通过conf获取到hbase集群的连接
        conn = ConnectionFactory.createConnection(conf);
    }

    //创建一张hbase表
    @Test
    public void createTable() throws IOException {
        //获取HbaseAdmin对象用来创建表
        HBaseAdmin admin = (HBaseAdmin) conn.getAdmin();
        //创建Htabledesc描述器,表描述器
        final HTableDescriptor worker = new HTableDescriptor(TableName.valueOf("worker"));
        //指定列族
        worker.addFamily(new HColumnDescriptor("info"));
        admin.createTable(worker);
        System.out.println("worker表创建成功!!");
    }

    //插入一条数据
    @Test
    public void putData() throws IOException {
        //需要获取一个table对象
        final Table worker = conn.getTable(TableName.valueOf("worker"));

        //准备put对象
        final Put put = new Put(Bytes.toBytes("110"));//指定rowkey

        //设置info列族下的addr为beijing
        put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("addr"), Bytes.toBytes("beijing"));
        //插入数据,参数类型是put
        worker.put(put);
        //准备list<puts>,可以执行批量插入
        //关闭table对象
        worker.close();
        System.out.println("插入数据到worker表成功!!");
    }


    //删除一条数据
    @Test
    public void deleteData() throws IOException {
        //需要获取一个table对象
        final Table worker = conn.getTable(TableName.valueOf("worker"));

        //准备delete对象
        final Delete delete = new Delete(Bytes.toBytes("110"));
//执行删除
        worker.delete(delete);
        //关闭table对象
        worker.close();
        System.out.println("删除数据成功!!");
    }

    //查询数据
    @Test
    public void getData() throws IOException {
        //准备table对象
        final Table worker = conn.getTable(TableName.valueOf("worker"));
        //准备get对象
        final Get get = new Get(Bytes.toBytes("110"));
        //指定查询某个列族或者列
        get.addFamily(Bytes.toBytes("info"));
        //执行查询
        final Result result = worker.get(get);
        //获取到result中所有cell对象
        final Cell[] cells = result.rawCells();
        //遍历打印
        for (Cell cell : cells) {
            final String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
            final String f = Bytes.toString(CellUtil.cloneFamily(cell));
            final String column = Bytes.toString(CellUtil.cloneQualifier(cell));
            final String value = Bytes.toString(CellUtil.cloneValue(cell));

            System.out.println("rowkey-->" + rowkey + "--;cf-->" + f + "---;column--->" + column + "--;value-->" + value);
        }
        worker.close();
    }


    //全表扫描
    @Test
    public void scanData() throws IOException {
        //准备table对象
        final Table worker = conn.getTable(TableName.valueOf("worker"));
        //准备scan对象
        final Scan scan = new Scan();

        //执行扫描
        final ResultScanner resultScanner = worker.getScanner(scan);
        for (Result result : resultScanner) {
            //获取到result中所有cell对象
            final Cell[] cells = result.rawCells();
            //遍历打印
            for (Cell cell : cells) {
                final String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
                final String f = Bytes.toString(CellUtil.cloneFamily(cell));
                final String column = Bytes.toString(CellUtil.cloneQualifier(cell));
                final String value = Bytes.toString(CellUtil.cloneValue(cell));
                System.out.println("rowkey-->" + rowkey + "--;cf-->" + f + ";column--->" + column + "--;value-->" + value);
            }
        }

        worker.close();
    }
//指定scan 开始rowkey和结束rowkey,这种查询方式建议使用,指定开始和结束rowkey区间避免全表扫描
@Test
public void scanStartEndData() throws IOException {
    //准备table对象
    final Table worker = conn.getTable(TableName.valueOf("worker"));
    //准备scan对象
    final Scan scan = new Scan();
    //指定查询的rowkey区间,rowkey在hbase中是以字典序排序
    scan.setStartRow(Bytes.toBytes("001"));
    scan.setStopRow(Bytes.toBytes("004"));
    //执行扫描
    final ResultScanner resultScanner = worker.getScanner(scan);
    for (Result result : resultScanner) {
        //获取到result中所有cell对象
        final Cell[] cells = result.rawCells();
        //遍历打印
        for (Cell cell : cells) {
            final String rowkey = Bytes.toString(CellUtil.cloneRow(cell));
            final String f = Bytes.toString(CellUtil.cloneFamily(cell));
            final String column = Bytes.toString(CellUtil.cloneQualifier(cell));
            final String value = Bytes.toString(CellUtil.cloneValue(cell));
            System.out.println("rowkey-->" + rowkey + "--;cf-->" + f + ";column--->" + column + "--;value-->" + value);
        }
    }

    worker.close();
}


    //释放连接
    @After
    public void realse() {
        if (conn != null) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printstacktrace();
            }
        }
    }
}

redis连接


public class JedisTest {
    //通过java程序访问redis数据库
    
    @Test
    //获得单一的jedis对象操作数据库
    public void test1() {
        //1.获得连接对象
        Jedis jedis = new Jedis("linux1", 6379);        //2.获取数据
        String username = jedis.get("username");
        System.out.println(username);
        //3.存储
        jedis.set("addr", "北京");
        System.out.println(jedis.get("addr"));
    }  //结果zhr      北京
    
    //通过jedis的pool获得jedis连接对象
    @Test
    public void test2() {
        //0.创建池子的配置对象
        JedisPoolConfig poolconfig = new JedisPoolConfig();
        poolconfig.setMaxIdle(30);//最大闲置个数
        poolconfig.setMinIdle(10);//最小闲置个数
        poolconfig.setMaxTotal(50);//最大连接数
        //1.创建一个redis的连接池
        JedisPool pool = new JedisPool(poolconfig,"linux1", 6379);
        //2.从池子中获取redis的连接资源
        Jedis jedis = pool.getResource();
        //3.操作数据库
        jedis.set("haha","123");
        System.out.println(jedis.get("haha"));
        //4.关闭资源
        jedis.close();
        pool.close();
    }
}

JedisPool使用升级

package com.zlx.jedis;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtils {
    
    private static JedisPool pool;
    
    static {
        //加载配置文件
        InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsstream("redis.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printstacktrace();
        }
        
        //获得池子对象
        JedisPoolConfig poolconfig = new JedisPoolConfig();
        poolconfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));//最大闲置个数
        poolconfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));//最小闲置个数
        poolconfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));//最大连接数
        pool = new JedisPool(poolconfig,pro.getProperty("redis.url"), Integer.parseInt(pro.get("redis.port").toString()));

    }
    
    //获得jedis资源的方法
    public static Jedis getJedis() {
        return pool.getResource();
    }
    
    public static void main(String[] args) {
        Jedis jedis = getJedis();
        System.out.println(jedis.get("haha"));
    }
    
}

redis.properties内容如下:

redis.maxIdle=30
redis.minIdle=10
redis.maxTotal=100
redis.url=linux1
redis.port=6379

JedisPool的配置参数大部分是由JedisPoolConfig的对应项来赋值的。
常见的几个参数就是如下:
maxTotal/maxActive:控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted。
maxIdle:控制一个pool最多有多少个状态为idle(空闲)的jedis实例;

连接redis集群

//
package com.zlx.redis;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.Set;

public class JedisClusterDemo {

    public static void main(String[] args) {


        JedisPoolConfig config = new JedisPoolConfig();
        Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
        jedisClusterNode.add(new HostAndPort("10.8.26.105", 7001));
        jedisClusterNode.add(new HostAndPort("10.8.26.105", 7002));
        jedisClusterNode.add(new HostAndPort("10.8.26.105", 7003));
        jedisClusterNode.add(new HostAndPort("10.8.26.105", 7004));
        jedisClusterNode.add(new HostAndPort("10.8.26.105", 7005));
        jedisClusterNode.add(new HostAndPort("10.8.26.105", 7006));
        jedisClusterNode.add(new HostAndPort("10.8.26.105", 7007));
        jedisClusterNode.add(new HostAndPort("10.8.26.105", 7008));
        JedisCluster jcd = new JedisCluster(jedisClusterNode, config);
        jcd.set("name:001", "zhangfei");
        String value = jcd.get("name:001");
        System.out.println("value:" + value);

    }
}

MysqL连接

JDBC工具类

import java.sql.*;

/**
 * JDBC工具类
 */
public class JDBCUtils {

    //1. 将连接信息定义为 字符串常量
    public static final String DRIVERNAME = "com.MysqL.jdbc.Driver";
    public static final String URL = "jdbc:MysqL://localhost:3306/db4?characterEncoding=UTF-8";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";

    //2.静态代码块
    static{
        try {
            //1.注册驱动
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            e.printstacktrace();
        }
    }

    //3.获取连接的 静态方法
    public static Connection getConnection(){
        try {
            //获取连接对象 并返回
            Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
            return connection;

        } catch (sqlException e) {
            e.printstacktrace();
            return null;
        }
    }

    //4.关闭资源的方法
    public static void close(Connection con, Statement statement){

        if(con != null && statement != null){

            try {
                statement.close();
                con.close();
            } catch (sqlException e) {
                e.printstacktrace();
            }
        }
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet){

        if(con != null && statement != null){

            try {
	resultSet.close();
                statement.close();
                con.close();              
            } catch (sqlException e) {
                e.printstacktrace();
            }
        }
    }

}

DML测试

package com.zlx.jdbc02;

import com.lagou.utils.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.sqlException;
import java.sql.Statement;

public class TestDML {

    /*
    * 插入数据
    * */
    @Test
    public void testInsert() throws sqlException {

        //1.通过JDBCUtils工具类 获取连接
        Connection con = JDBCUtils.getConnection();

        //2.获取Statement对象
        Statement statement = con.createStatement();

        //2.1 编写sql
        String sql = "insert into jdbc_user values(null,'张百万','123','2020/11/11')";

        //2.2 执行sql
        int i = statement.executeUpdate(sql);
        System.out.println(i);

        //3.关闭流
        JDBCUtils.close(con,statement);
    }

    /*
    * 更新操作 根据id修改用户名
    * */
    @Test
    public void testUpdate() throws sqlException {

        Connection connection = JDBCUtils.getConnection();

        Statement statement = connection.createStatement();

        String sql = "update jdbc_user set username = '刘能' where id = 1";

        statement.executeUpdate(sql);

        JDBCUtils.close(connection,statement);
    }

    /*
    * 删除操作
    * 删除 id为 1 和 2 的数据
    *
    * */
    @Test
    public void testDelete() throws sqlException {

        Connection connection = JDBCUtils.getConnection();
        Statement statement = connection.createStatement();

        String sql = "delete from jdbc_user where id in(1,2)";
        statement.executeUpdate(sql);

        JDBCUtils.close(connection,statement);
    }
}

DQL测试

package com.zlx.jdbc02;

import com.lagou.utils.JDBCUtils;

import java.sql.*;

public class TestDQL {

    // 查询姓名为张百万的一条记录
    public static void main(String[] args) throws sqlException {
        //1.获取连接
        Connection connection = JDBCUtils.getConnection();
        //2.创建Statement对象
        Statement statement = connection.createStatement();

        //3. 编写sql
        String sql = "select * from jdbc_user where username = '张百万'";
        ResultSet resultSet = statement.executeQuery(sql);

        //4.处理结果集
        while(resultSet.next()){
            // 通过列名的方式获取
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            String password = resultSet.getString("password");
            Date birthday = resultSet.getDate("birthday");

            System.out.println(id + " : " + username + " : " + password + " : "  + birthday );
        }

        //5.释放资源
        JDBCUtils.close(connection,statement,resultSet);
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐