Java连接Redis和(BDB)Berkeley DB

原创
2017/06/21 00:04
阅读数 46

在Java程序中使用Redis之前,需要确保在机器上安装了Redis的Java驱动程序和Java环境。

一、安装Redis

sudo apt-get install redis-server

二、配置Redis Java驱动程序

  下载最新版本jedis Java驱动

wget http://central.maven.org/maven2/redis/clients/jedis/2.9.0/jedis-2.9.0.jar

将jedis包含到类路径中。(如eclipse中的配置路径加上给文件)

三、代码

package www.zjptcc.wxw.jdbctest;
import java.util.List;
import redis.clients.jedis.Jedis;

public class RedisJava {

	private static Jedis jedis;

	public static void main(String[] args) {
		jedis = new Jedis("localhost",6379);   //Jedis("localhost")
		System.out.println("Connection to server sucessfully");
		// set the data in redis string
		jedis.set("tutorial-name", "Redis tutorial");
		// Get the stored data and print it
		System.out.println("Stored string in redis:: " + jedis.get("tutorial-name"));
		

	      //store data in redis list 
	      jedis.lpush("tutorial-list", "Redis"); 
	      jedis.lpush("tutorial-list", "Mongodb"); 
	      jedis.lpush("tutorial-list", "Mysql"); 
	      jedis.lpush("tutorial-list", "Postgres"); 
	      // Get the stored data and print it 
	      List<String> list = jedis.lrange("tutorial-list", 0 ,5); 
	      for(int i = 0; i<list.size(); i++) { 
	         System.out.println("Stored string in redis:: "+list.get(i)); 
	      } 
	}

}

运行结果:

Connection to server sucessfully
Stored string in redis:: Redis tutorial
Stored string in redis:: Postgres
Stored string in redis:: Mysql
Stored string in redis:: Mongodb
Stored string in redis:: Redis
Stored string in redis:: Postgres
Stored string in redis:: Mysql

四、jedis客户端

上面的java程序运行三次后有12条数据存入tutorial-list,下面的命令删除其中的8条

$ redis-cli 
127.0.0.1:6379> lrange tutorial-list 0 100
 1) "Postgres"
 2) "Mysql"
 3) "Mongodb"
 4) "Redis"
 5) "Postgres"
 6) "Mysql"
 7) "Mongodb"
 8) "Redis"
 9) "Postgres"
10) "Mysql"
11) "Mongodb"
12) "Redis"
127.0.0.1:6379> rpop tutorial-list
"Redis"
127.0.0.1:6379> rpop tutorial-list
"Mongodb"
127.0.0.1:6379> rpop tutorial-list
"Mysql"
127.0.0.1:6379> rpop tutorial-list
"Postgres"
127.0.0.1:6379> rpop tutorial-list
"Redis"
127.0.0.1:6379> rpop tutorial-list
"Mongodb"
127.0.0.1:6379> rpop tutorial-list
"Mysql"
127.0.0.1:6379> rpop tutorial-list
"Postgres"
127.0.0.1:6379> lrange tutorial-list 0 100
1) "Postgres"
2) "Mysql"
3) "Mongodb"
4) "Redis"
127.0.0.1:6379> 

五、安装Berkeley DB

ubuntu18.04

 sudo apt install libdb-je-java libdb-java libdb-java-dev libdb5.3-java libdb5.3-java-dev libdb++-dev libdb-dev libdb5.3 libdb5.3++ libdb5.3++-dev libdb5.3-dev libdb5.3

把/usr/share/java/db-je-3.3.98.jar拷贝到java路径

package www.zjptcc.wxw.jdbc.BerkeleyDB;


import java.io.File;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

/**
 * BerkeleyDB java的简单使用
 * @author Xiaohua 
 *
 */
public class Test {
	
	//此数据库的优点
	//大数据的支持,能够支持millions的记录,而且更可能是硬件出现瓶颈而不是je
	//数据库环境支持。数据库环境能够一次配置多个数据库或者一个数据库;环境也能够管理并发和事务
	//多线程和多进程的支持
	//支持事务
	//支持内存缓存
	//支持索引
	//日志记录
	private static String dbEnv = "/home/mymotif/workspace/jdk8/src/www/zjptcc/wxw/jdbc/BerkeleyDB";

	public static void main(String[] args) {
		Environment myDbEnvironment = null;
		Database myDatabase = null;
		try {
			EnvironmentConfig envConfig = new EnvironmentConfig();// 配置环境变量
			envConfig.setAllowCreate(true);
			File f=new File(dbEnv);
			if(!f.exists()){
				f.mkdirs();
			}
			myDbEnvironment = new Environment(f, envConfig);

		} catch (DatabaseException dbe) {
		}
		try {
			DatabaseConfig dbConfig = new DatabaseConfig();// 打开数据库
			dbConfig.setAllowCreate(true);
			myDatabase = myDbEnvironment.openDatabase(null, "myDatabase",
					dbConfig);

		} catch (DatabaseException dbe2) {

		}
//存储数据
		String aKey = "key4";
		String aData = "data";
		try {
			DatabaseEntry theKey = new DatabaseEntry(aKey.getBytes("UTF-8"));
			DatabaseEntry theData = new DatabaseEntry(aData.getBytes("UTF-8"));
			myDatabase.put(null, theKey, theData);
//			myDbEnvironment.sync();
			System.out.println(myDatabase.count());
		} catch (Exception e) {

		}

		// 关闭,应该会自己主动提交
		try {
			if (myDatabase != null) {
				myDatabase.close();
			}
			if (myDbEnvironment != null) {
				myDbEnvironment.cleanLog(); //  在关闭环境前清理下日志
				myDbEnvironment.close();
			}
		} catch (DatabaseException dbe) {

		}
	}
}

c++语言:

// g++ test.cpp -o test -ldb -ldb_cxx

#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <db_cxx.h>
#include <db.h>

int main()
{ 
//Creat and Open my_db.db 
Db db(NULL, 0); // Instantiate the Db object
u_int32_t oFlags = DB_CREATE; // Open flags;
try {
// Open the database
db.open(NULL, // Transaction pointer
"./my_db.db", // Database file name
  NULL, // Optional logical database name
  DB_BTREE, // Database access method
  oFlags, // Open flags
  0); // File mode (using defaults)
// DbException is not subclassed from std::exception, so
// need to catch both of these.
} 
catch(DbException &e) 
{
// Error handling code goes here
std::cerr << e.what() << std::endl;
} 
catch(std::exception &e) 
{
// Error handling code goes here
std::cerr << e.what() << std::endl;
}

//Put Data into my_db.db
char *description =  (char *) "Grocery bill.";
float money = 122;
Dbt pkey(&money, sizeof(float));
Dbt pdata(description, strlen(description) + 1);
int ret = db.put(NULL, &pkey, &pdata, DB_NOOVERWRITE);
if (ret == DB_KEYEXIST)
{
db.err(ret, "Put failed because key %f already exists", money);
}
else
{printf("db: %s: data stored.\n",  (char *) pdata.get_data());}
//Get Data from my_db.db

// Use our own memory to retrieve the float.
// For data alignment purposes.
//pkey.set_data(&money);
//pkey.set_ulen(sizeof(float));
//pkey.set_flags(DB_DBT_USERMEM);
db.get(NULL, &pkey, &pdata, 0);
printf("db: %s=%f: data get.\n", (char *)pdata.get_data(),money);
//Delet Data from my_db.db
db.del(NULL, &pkey, 0);
//Close my_db.db
try {
// Close the database
db.close(0);
// DbException is not subclassed from std::exception, so
// need to catch both of these.
} 
catch(DbException &e) {
// Error handling code goes here
std::cerr << e.what() << std::endl;
} 
catch(std::exception &e) {
// Error handling code goes here
std::cerr << e.what() << std::endl;
}
return(0);
}

c语言

/*
 *   
 *   gcc testdb.c -o testdb -ldb
 * */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <db.h>

#define DATABASE "test.db"

typedef struct _data_struct {
    int data_id;
    char data[20];
} data_struct;

int main()
{
    DBT key, data;
    DB *dbp;
    int ret;
    data_struct my_data;

    ret = db_create(&dbp, NULL, 0);  // create the DB handle
    if (ret != 0)
    {
        perror("create");
        return 1;
    }

    ret = dbp->open(dbp, NULL, DATABASE, NULL, DB_BTREE, DB_CREATE, 0);  // open the database
    if (ret != 0)
    {
        perror("open");
        return 1;
    }
    my_data.data_id = 1;
    strcpy(my_data.data, "some data");

    memset(&key, 0, sizeof(DBT));
    memset(&data, 0, sizeof(DBT));

    key.data = &(my_data.data_id);
    key.size = sizeof(my_data.data_id);
    data.data = &my_data;
    data.size = sizeof(my_data);

    ret = dbp->put(dbp, NULL, &key, &data, DB_NOOVERWRITE);  // add the new data into the database
    if (ret != 0)
    {
        printf("Data ID exists\n");
    }

    dbp->close(dbp, 0);   // close the database

    return 0;
}

参考:

Redis 列表(List)

http://www.runoob.com/redis/redis-lists.html

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部