【nosql-redis】java直接操作redis
阿新 • • 發佈:2018-11-30
redis入門,百度網盤
連結: https://pan.baidu.com/s/11onVTGqf7uyCGxkoQOxdTw 密碼: csef
1 redis.properties
直接配置在classpath下面
#*****************jedis連線引數設定*********************# #redis伺服器ip # #測試環境 #redis.ip=192.168.87.211 #正式環境 redis.ip=139.198.126.229 #redis伺服器埠號# redis.port=6479 #redis 測試密碼 password #redis.password=hesvit*0522 #線上redies密碼 redis.password=hesvit #************************jedis池引數設定*******************# #jedis的最大分配物件# jedis.pool.maxActive=300 #jedis最大儲存idel狀態物件數 # jedis.pool.maxIdle=1000 #jedis池沒有物件返回時,最大等待時間 # jedis.pool.maxWait=1500 #jedis呼叫borrowObject方法時,是否進行有效檢查# jedis.pool.testOnBorrow=true #jedis呼叫returnObject方法時,是否進行有效檢查 # jedis.pool.testOnReturn=true
2 RedisPool.java
package com.hesvit.common.util;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class MyJedisPool {
private static Logger logger = LoggerFactory.getLogger(MyJedisPool.class);
private static JedisPool pool;
// 靜態程式碼初始化池配置
static {
try {
Properties props = new Properties();
props.load(MyJedisPool.class.getClassLoader().getResourceAsStream("redis.properties" ));
// 建立jedis池配置例項
JedisPoolConfig config = new JedisPoolConfig();
// 設定池配置項值
// config.setMaxActive(Integer.valueOf(props.getProperty("jedis.pool.maxActive")));
/*
* config.setMaxIdle(Integer.valueOf(props.getProperty(
* "jedis.pool.maxIdle")));
*
* config.setMaxWaitMillis(Long.valueOf(props.getProperty(
* "jedis.pool.maxWait")));
*
* config.setTestOnBorrow(Boolean.valueOf(props.getProperty(
* "jedis.pool.testOnBorrow")));
*
* config.setTestOnReturn(Boolean.valueOf(props.getProperty(
* "jedis.pool.testOnReturn")));
*/
config.setMaxTotal(200);
config.setMaxIdle(50);
config.setMinIdle(8);// 設定最小空閒數
config.setMaxWaitMillis(10000);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
// Idle時進行連線掃描
config.setTestWhileIdle(true);
// 表示idle object evitor兩次掃描之間要sleep的毫秒數
config.setTimeBetweenEvictionRunsMillis(30000);
// 表示idle object evitor每次掃描的最多的物件數
config.setNumTestsPerEvictionRun(10);
// 表示一個物件至少停留在idle狀態的最短時間,然後才能被idle object
// evitor掃描並驅逐;這一項只有在timeBetweenEvictionRunsMillis大於0時才有意義
config.setMinEvictableIdleTimeMillis(60000);
// 根據配置例項化jedis池
// pool = new JedisPool(config, props.getProperty("redis.ip"),
// Integer.valueOf(props.getProperty("redis.port")));
String password = props.getProperty("redis.password");
if (StringUtils.isBlank(password)) {
password = null;
}
pool = new JedisPool(config, props.getProperty("redis.ip"),
Integer.valueOf(props.getProperty("redis.port")), 3000, password);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 獲得jedis物件
*
*/
public synchronized static Jedis getJedisObject() {
logger.info("獲取redies");
Jedis jedis = null;
if (pool != null) {
try {
jedis = pool.getResource();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
return jedis;
}
/**
* 歸還jedis物件
*
*/
public synchronized static void recycleJedisOjbect(Jedis jedis) {
logger.info("釋放資源.....");
if (jedis != null) {
jedis.close();
}
}
/**
*
* 測試jedis池方法
*
*/
public static void main(String[] args) {
// Properties props = new Properties();
// System.out.println(props.getProperty("jedis.pool.maxIdle"));
Jedis jedis = getJedisObject();// 獲得jedis例項
// 獲取jedis例項後可以對redis服務進行一系列的操作
jedis.set("name", "zhuxun");
jedis.expire("name", 5000);
System.out.println(jedis.get("name"));
jedis.del("name");
System.out.println(jedis.exists("name"));
recycleJedisOjbect(jedis); // 將 獲取的jedis例項物件還回池中
}
}
3 redisUtil.java的使用
實際專案的一個例子
@Component
public class RedisUtil {
// 快取所有App使用者
private static String ALL_APP_USERS = "all_app_users";
/**
* 獲取所有的APP 使用者
* liuping
*/
@SuppressWarnings({ "deprecation", "unchecked" })
public static List<User> getAllAppUsers() {
Jedis redis = MyJedisPool.getJedisObject();// 獲得jedis例項
List<User> users = new ArrayList<>();
try {
String strAppUser = redis.get(ALL_APP_USERS);
if (StringUtils.isBlank(strAppUser)) {
users = refreshAppUser(redis);
} else {
JSONArray jsonArray = JSONArray.fromObject(strAppUser);
users = JSONArray.toList(jsonArray, User.class);
}
} catch (Exception e) {
logger.error("Failed to get app user from redis: {}", e.getMessage());
} finally {
MyJedisPool.recycleJedisOjbect(redis);
}
return users;
}
/**
* 重新整理App使用者列表
* liuping
*/
public static List<User> refreshAppUser(Jedis redis) {
if (redis == null)
redis = MyJedisPool.getJedisObject();// 獲得jedis例項
List<User> users = new ArrayList<>();
try {
User user = new User();
user.setLimit(-1);
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
UserService service = (UserService) context.getBean("userService");
users = service.selectByIndex(user);
if (null != users) {
JSONArray jsonArray = JSONArray.fromObject(users);
String struser = String.valueOf(jsonArray);
redis.set(ALL_APP_USERS, struser);
redis.expire(ALL_APP_USERS, EXPIRE_2_HOUR); // 設定過期時間
}
} catch (Exception e) {
logger.error("Failed to get wxuser from redis: {}", e.getMessage());
} finally {
MyJedisPool.recycleJedisOjbect(redis);
}
return users;
}