mogodb,redis,mysql的Java连接

1.读取配置文件的配置项信息

/**
 * 读取配置文件中的配置项
 * 
 *
 */
public class Configures {

private static String URL = System.getenv("STAFF_PATH") + "/mqttweb/constant.properties";

private static Properties prop = new Properties();


public static void init() {
if (prop == null || prop.size() == 0) {
try {
// 读取属性文件URL
InputStream in = new BufferedInputStream(new FileInputStream(URL));
prop.load(in); /// 加载属性列表
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


public static String getValue(String key) {
if (StringUtils.isNotEmpty(key)) {
return prop.getProperty(key);
}
return null;


}


}

 System.getenv("STAFF_PATH")  是读取系统变量的配置信息(如下图)


2. 配置项的内容(constant.properties的内容)

#mongoDB的ip
MONGODB_IP=127.0.0.1




#mongoDB的端口
MONGODB_PORT=27017
#mongoDB连接的最大空闲时间
MONGODB_MAX_IDLE_TIME=60000
#mongodb的账号
MONGODB_USER=staff
#mongodb的密码
MONGODB_PASSWD=123456




#redis的IP
REDIS_IP=127.0.0.1
#redis的端口
REDIS_PORT=6379
#redis可连接实例的最大数目
REDIS_MAX_ACTIVE=1024
#redis pool最多为空闲的实例,默认为8
REDIS_MAX_IDLE=200
#redis等待可连接的最大时间,单位毫秒
REDIS_MAX_WAIT=1000
#redis连接密码
REDIS_PASSWD=123456
#在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
REDIS_TEST_ON_BORROW=true;
#redis超时时间
REDIS_TIME_OUT=60000


#mqtt发布的主题(阻塞线程的标识,通知mqtt服务器,队列空了)
#发布到主题
MQTT_TOPIC=register/test
#MQTT连接IP+端口
MQTT_BROKER=tcp://127.0.0.1:1883
#mqtt连接的客户端ID
MQTT_CLIENTID=test
#MQTT发送的信息
MQTT_INFO=idle




#thread pool 线程池允许的最大并发数
THREAD_NUMBER=4
#等待时间
WAIT_TIME=60000


#socket连接模块
SOCKET_IP=172.168.1.142
SOCKET_PORT=11111




#mysql连接
MYSQL_URL=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
MYSQL_USERNAME=root
MYSQL_PASSWD=123456


3.连接

  1 .mongodb

package com.hand.utils;


import java.util.ArrayList;
import java.util.List;


import org.bson.Document;


import com.hand.method.Configures;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;


public class MongoDB {
private static MongoClient mongoClient = null;
private static String IP = "192.168.10.250";
//private static String IP = "192.168.10.117";
//private static String IP = "192.168.10.226";
// private static String IP = "192.168.10.250";
// 10.150
private static Integer PORT = 27017;
private static Integer MAX_IDLE_TIME = 60000;


/**
* mongodb连接

* @return
*/
public MongoDB() {
List<ServerAddress> addresses = new ArrayList<ServerAddress>();
if (StringUtils.isNotEmpty(Configures.getValue("MONGODB_IP"))) {
IP = Configures.getValue("MONGODB_IP").trim();
}
if (StringUtils.isNotEmpty(Configures.getValue("MONGODB_PORT"))) {
PORT = Integer.valueOf(Configures.getValue("MONGODB_PORT").trim());
}
if (StringUtils.isNotEmpty(Configures.getValue("MONGODB_MAX_IDLE_TIME"))) {
MAX_IDLE_TIME = Integer.valueOf(Configures.getValue("MONGODB_MAX_IDLE_TIME").trim());
}
ServerAddress address3 = new ServerAddress(IP, PORT);
addresses.add(address3);
MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
builder.maxConnectionIdleTime(MAX_IDLE_TIME);
MongoClientOptions opts = builder.build();
mongoClient = new MongoClient(addresses, opts);
}


/**
* 获取mongodb collection

* @param dbname
* @param colname
* @return
*/
public MongoCollection<Document> getCollection(String dbname, String colname) {
// 数据库名 表名不为空
if (StringUtils.isNotEmpty(dbname) && StringUtils.isNotEmpty(colname)) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname); // 获取db
MongoCollection<Document> districtTitleCollection = mongoDatabase.getCollection(colname);// 获取collection
return districtTitleCollection;
} else {
return null;
}


}


/**
* 获取数据库连接

* @param dbname
* @return
*/
public MongoDatabase getDatabase(String dbname) {
return mongoClient.getDatabase(dbname);
}


/**
* 获取集合连接

* @param colname
* @param mongoDatabase
* @return
*/
public MongoCollection<Document> getCollection(String colname, MongoDatabase mongoDatabase) {
return mongoDatabase.getCollection(colname);
}


public static void close(MongoClient mongoClient) {
mongoClient.close();
}


public static void main(String[] args) {
// update();
MongoDB mongodb = new MongoDB();
MongoCollection<Document> col = mongodb.getCollection("hand_hygiene", "actions");
col.updateOne(new Document().append("_id", "1"),
new Document().append("$addToSet", new Document().append("info", "2")));
}
}


2. redis

package com.hand.utils;


import java.util.Map;


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


public class RedisUtils {
// Redis服务器IP
private static String ADDR = "192.168.10.4";
// Redis的端口号
private static int PORT = 6379;
// 可连接实例的最大数目,默认值为8
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = 1024;
// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 200;
// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = 1000;
private static Integer TIME_OUT = 60000;
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
//private static String PASSWD = "123456";


/**
* 初始化Redis连接池
*/
public static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
// if (StringUtils.isNotEmpty(Configures.getValue("REDIS_IP"))) {
// ADDR = Configures.getValue("REDIS_IP").trim();
// }
// if (StringUtils.isNotEmpty(Configures.getValue("REDIS_PORT"))) {
// PORT = Integer.valueOf(Configures.getValue("REDIS_PORT").trim());
// }
// if
// (StringUtils.isNotEmpty(Configures.getValue("REDIS_MAX_ACTIVE")))
// {
// MAX_ACTIVE =
// Integer.valueOf(Configures.getValue("REDIS_MAX_ACTIVE").trim());
// }
// if
// (StringUtils.isNotEmpty(Configures.getValue("REDIS_MAX_IDLE"))) {
// MAX_IDLE =
// Integer.valueOf(Configures.getValue("REDIS_MAX_IDLE").trim());
// }
// if
// (StringUtils.isNotEmpty(Configures.getValue("REDIS_MAX_WAIT"))) {
// MAX_WAIT =
// Integer.valueOf(Configures.getValue("REDIS_MAX_WAIT").trim());
// }
// if (StringUtils.isNotEmpty(Configures.getValue("REDIS_PASSWD")))
// {
// PASSWD = Configures.getValue("REDIS_PASSWD").trim();
// }
// if
// (StringUtils.isNotEmpty(Configures.getValue("REDIS_TEST_ON_BORROW")))
// {
// TEST_ON_BORROW =
// Boolean.valueOf(Configures.getValue("REDIS_TEST_ON_BORROW").trim());
// }
// if
// (StringUtils.isNotEmpty(Configures.getValue("REDIS_TIME_OUT"))) {
// TIME_OUT =
// Integer.valueOf(Configures.getValue("REDIS_TIME_OUT").trim());
// }
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR, PORT, TIME_OUT);
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 在多线程环境同步初始化
*/
private synchronized static void poolInit() {
if (jedisPool == null) {
initialPool();
}
}


/**
* 同步获取Jedis实例

* @return
*/
public static Jedis getJedis() {
Jedis jedis = getjedisCon();
Integer i = 1;
while (jedis == null && i < 3) {
System.out.println("第" + i + "次,连接失败");
jedis = getjedisCon();
i++;
}
return jedis;
}


/**
* 获取Jedis实例

* @return
*/
public static Jedis getjedisCon() {
if (jedisPool == null) {
poolInit();
}
Jedis resource = null;
try {
if (jedisPool != null) {
resource = jedisPool.getResource();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resource != null) {
// returnResource(resource);
}
}
return resource;
}


/**
* 不在redis连接池中获取jedis实例

* @return
*/
public static Jedis getSingleJedis() {
Jedis jedis = new Jedis(ADDR, PORT);
//jedis.auth(PASSWD);
return jedis;
}

/**
* 获取Map值

* @param mapKey
*            valueKey
*/
public static String getStringFromRedis(String mapKey, String valueKey) {
Jedis jedis = getJedis();
String val = null;
if(jedis != null){
try {
val = jedis.hget(mapKey, valueKey);
} catch (Exception e) {
e.printStackTrace();
} finally {
close(jedis);
}
}
return val;
}


/**
* 取到队列的最后一个元素,并将其移除

* @param listName
* @return
*/
public static String rpop(String listName) {
Jedis jedis = RedisUtils.getJedis();
String s = null;
try {
s = jedis.rpop(listName);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return s;


}


/**
* 获取散列hash中某域的值

* @param key
* @param field
* @return
*/
public static String hget(String key, String field) {
Jedis jedis = RedisUtils.getJedis();
String val = null;
try {
val = jedis.hget(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
return val;


}


/**
* 移除散列中的某个键

* @param key
* @param field
*/
public static void hdel(String key, String field) {
Jedis jedis = RedisUtils.getJedis();
try {
jedis.hdel(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}


/**
* 设置散列某个域的值

* @param key
* @param field
* @param value
*/
public static void hset(String key, String field, String value) {
Jedis jedis = RedisUtils.getJedis();
try {
jedis.hset(key, field, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}


/**
* 获取散列

* @param key
* @return
*/
public static Map<String, String> hgetAll(String key) {
Jedis jedis = RedisUtils.getJedis();
Map<String, String> map = null;
try {
map = jedis.hgetAll(key);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}

/**
* 释放jedis资源

* @param jedis
*/
public static void close(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}

}

3.mysql 

package com.hand.utils;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import com.hand.method.Configures;


public class MysqlUtil {
//驱动信息   
private static String URL = "jdbc:mysql://192.168.10.4:3307/hand?useUnicode=true&characterEncoding=utf8&useSSL=false";
private static String USERNAME = "root";
private static String PASSWD = "123456";
static {
if (StringUtils.isNotEmpty(Configures.getValue("MYSQL_URL"))) {
URL = Configures.getValue("MYSQL_URL").trim();
}
if (StringUtils.isNotEmpty(Configures.getValue("MYSQL_USERNAME"))) {
USERNAME = Configures.getValue("MYSQL_USERNAME").trim();
}
if (StringUtils.isNotEmpty(Configures.getValue("MYSQL_PASSWD"))) {
PASSWD = Configures.getValue("MYSQL_PASSWD").trim();
}
}


public static Connection getConnection() {
try {
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWD);
return con;
} catch (SQLException se) {
getConnection();
}
return null;
}


public static ResultSet query(Connection conn, String sql) {
// statement创建对象
try {
Statement statement = conn.createStatement();
// 返回的结果集
ResultSet rs = statement.executeQuery(sql);
return rs;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}


public static Integer update(Connection conn, String sql) {
// statement创建对象
try {
Statement statement = conn.createStatement();
Integer i = statement.executeUpdate(sql);
return i;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}


public static void main(String[] args) throws Exception {
Connection conn = getConnection();
String sql = "select * from synchro_data";
ResultSet rs = query(conn, sql);
while(rs.next()){
System.out.println(rs.getString("id"));
}
//Connection conn = getConnection("", "", "");
// 创建sql
// String sql = "select * from test where name LIKE '%����%'";
// ResultSet rs = query(conn, sql);
//String sql = "insert test(name,gmt_created,gmt_modified) values" + "('����',now(),now())";
// 执行结果
//Integer rs = update(conn, sql);
//System.out.println(rs);
// while (rs.next()) {
// // ������
// System.out.println(rs.getString("id") + "\t" + rs.getString("name") +
// "\t" + rs.getString("gmt_created")
// + "\t" + rs.getString("gmt_modified"));
// }
// rs.close();
//conn.close();
}


}


2.2packacom.hand.utils;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import com.hand.method.Configures;


public class MysqlUtil {
//驱动信息   
private static String URL = "jdbc:mysql://192.168.10.4:3307/hand?useUnicode=true&characterEncoding=utf8&useSSL=false";
private static String USERNAME = "root";
private static String PASSWD = "123456";
static {
if (StringUtils.isNotEmpty(Configures.getValue("MYSQL_URL"))) {
URL = Configures.getValue("MYSQL_URL").trim();
}
if (StringUtils.isNotEmpty(Configures.getValue("MYSQL_USERNAME"))) {
USERNAME = Configures.getValue("MYSQL_USERNAME").trim();
}
if (StringUtils.isNotEmpty(Configures.getValue("MYSQL_PASSWD"))) {
PASSWD = Configures.getValue("MYSQL_PASSWD").trim();
}
}


public static Connection getConnection() {
try {
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWD);
return con;
} catch (SQLException se) {
getConnection();
}
return null;
}


public static ResultSet query(Connection conn, String sql) {
// statement创建对象
try {
Statement statement = conn.createStatement();
// 返回的结果集
ResultSet rs = statement.executeQuery(sql);
return rs;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}


public static Integer update(Connection conn, String sql) {
// statement创建对象
try {
Statement statement = conn.createStatement();
Integer i = statement.executeUpdate(sql);
return i;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}


public static void main(String[] args) throws Exception {
Connection conn = getConnection();
String sql = "select * from synchro_data";
ResultSet rs = query(conn, sql);
while(rs.next()){
System.out.println(rs.getString("id"));
}
//Connection conn = getConnection("", "", "");
// 创建sql
// String sql = "select * from test where name LIKE '%����%'";
// ResultSet rs = query(conn, sql);
//String sql = "insert test(name,gmt_created,gmt_modified) values" + "('����',now(),now())";
// 执行结果
//Integer rs = update(conn, sql);
//System.out.println(rs);
// while (rs.next()) {
// // ������
// System.out.println(rs.getString("id") + "\t" + rs.getString("name") +
// "\t" + rs.getString("gmt_created")
// + "\t" + rs.getString("gmt_modified"));
// }
// rs.close();
//conn.close();
}


}




22




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值