java怎么配置radis,java关于redis的快速配置

标签:

1.关于Jedis安装配置很简单,我主要写一个,能够快速使用redis的工具类,首先导入依赖, 就一个 jedis 最好选用老一点版本

redis.clients

jedis

2.6.0

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 =jedis.get(key);

try {

jedis=RedisPool.getJedis();

result=jedis.get(key);

}catch (Exception e){

RedisPool.returnBrokenResource(jedis);

return result;

}

RedisPool.returnResource(jedis);

return result;

}

写完这些基本上就可以在项目中使用redis了

标签:

来源: https://www.cnblogs.com/xietao2282/p/9801445.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值