元素周期表

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了

posted on 2018-10-16 23:26  元素周期表  阅读(1539)  评论(0编辑  收藏  举报

导航