java關於redis的快速配置


1.關於Jedis安裝配置很簡單,我主要寫一個,能夠快速使用redis的工具類,首先導入依賴, 就一個 jedis 最好選用老一點版本     

  <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.6.0</version>
</dependency>

2.寫一個jedis連接池 這里的參數最好是寫在配置文件中   因為以后隨時都有可能改動  可寫在*.properties文件中方便讀取

 

public class RedisPool {
private static JedisPool pool;//jedis連接池
private static Integer maxTotal= 20;//最大連接數
private static Integer maxIdle=10;//最大的Idle(空閑)狀態的Jedis實例個數
private static Integer minIdle=2; //最小的Idle(空閑)狀態的Jedis實例個數
private static String redisIp="127.0.0.1"; //根據情況而定IP
private static Integer redisPort=6379; //端口視情況而定
private static Boolean testOnBorrow=true; //在borrow一個jedis實例的時候,是否需要驗正作,如果是賦值true
private static Boolean testOnReturn=true; //在return。。。。

private static void initPool(){
JedisPoolConfig config=new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
config.setBlockWhenExhausted(true);//連接耗盡時是否阻塞
pool= new JedisPool(config,redisIp,redisPort,1000*2);
}
static {
initPool();
}
public static Jedis getJedis(){
return pool.getResource();
}
public static void returnBrokenResource(Jedis jedis){
pool.returnBrokenResource(jedis);
}
public static void returnResource(Jedis jedis){
pool.returnResource(jedis);
}

public static void main(String[] args) {
Jedis jedis =pool.getResource();

jedis.set("testkey","myvalue");
returnResource(jedis);
System.out.println("z測試完畢");
}
3.在寫一個Redis工具類 里面的方法可以自定義很多是自己需要而寫 我這里就簡單的一個get set
public class RedisPoolUtil {
public static String set(String key,String value){
Jedis jedis=null;
String result=null;
try {
jedis =RedisPool.getJedis();
result=jedis.set(key,value);
}catch (Exception e){
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
}

public static String get(String key){
Jedis jedis=null;
String result=null;
try {
jedis=RedisPool.getJedis();
result=jedis.get(key);
}catch (Exception e){
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
}
寫完這些基本上就可以在項目中使用redis了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM