1.关于Jedis安装配置很简单,我主要写一个,能够快速使用redis的工具类,首先导入依赖, 就一个 jedis 最好选用老一点版本 !-- https://mvnrepository.com/artifact/redis.clients/jedis --dependency ...
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 =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了
本文标题为:java关于redis的快速配置
基础教程推荐
- MySQL实现批量插入测试数据的方式总结 2023-08-12
- mysql查询FIND_IN_SET REGEXP实践示例 2023-07-27
- 关于对MongoDB索引的一些简单理解 2023-07-15
- SQL数据库十四种案例介绍 2023-08-12
- Redis五种数据类型详解 2023-07-13
- Oracle 数据库启动过程的三阶段、停库四种模式详解 2023-07-23
- 还原Sql Server数据库BAK备份文件的3种方式以及常见错误总结 2023-07-29
- centos7中redis安装 2023-09-12
- Redis中的BigKey问题排查与解决思路详解 2023-07-13
- 在阿里云CentOS 6.8上安装Redis 2023-09-12
