Redis的使用及参考代码
Redis是一种完全开源免费,高性能的key-value数据库或数据结构服务器,因为value值可以是字符串,哈希(map),列表list,集合等.
Jedis 是 Redis 官方首选的 Java 客户端开发包。
使用Jedis开发步骤:
1. 如果是maven项目,在pom.xml里引入下面的dependency
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
2. 在配置文件里配置redis的ip和端口号,redis默认端口号是6379
3. 连接redis:两种方式,使用连接池和不使用连接池,redis连接类似数据库连接,频繁的打开连接和关闭连接影响性能,使用连接池更好
3.1. 不使用连接池
//连接redis ,redis的默认端口是6379
Jedis jedis = new Jedis ("localhost",6379);
//验证密码,如果没有设置密码这段代码省略
jedis.auth("password");
jedis.connect();//连接
jedis.set("key","value");
String value = jedis.get("key");
jedis.disconnect();//断开连接
3.2 使用redis池
下面引用https://blog.csdn.net/zxp2624161989/article/details/53769549这位博主的代码:
ReentrantLock版
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; /**
* Redis 工具类
*/
public class JedisUtil { protected static ReentrantLock lockPool = new ReentrantLock();
protected static ReentrantLock lockJedis = new ReentrantLock(); protected static Logger logger = Logger.getLogger(JedisUtil.class); //Redis服务器IP
private static String ADDR_ARRAY = "xxx.xxx.xxx.xxx"; //Redis的端口号
private static int PORT = 6379; //访问密码
private static String AUTH = "http://blog.csdn.net/unix21";
//可用连接实例的最大数目,默认值为8;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = 8; //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 8; //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = 3000; //超时时间
private static int TIMEOUT = 10000; //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = false; private static JedisPool jedisPool = null; /**
* redis过期时间,以秒为单位
*/
public final static int EXRP_HOUR = 60 * 60; //一小时
public final static int EXRP_DAY = 60 * 60 * 24; //一天
public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一个月 /**
* 初始化Redis连接池
*/
private static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT, AUTH);
} catch (Exception e) {
logger.error("First create JedisPool error : " + e);
try {
//如果第一个IP异常,则访问第二个IP
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT, AUTH);
} catch (Exception e2) {
logger.error("Second create JedisPool error : " + e2);
}
}
} /**
* 在多线程环境同步初始化
*/
private static void poolInit() {
lockPool.lock();
try {
if (jedisPool == null) {
initialPool();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lockPool.unlock();
}
} public static Jedis getJedis() {
lockJedis.lock();
if (jedisPool == null) {
poolInit();
}
Jedis jedis = null;
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
}
} catch (Exception e) {
logger.error("Get jedis error : " + e);
} finally {
returnResource(jedis);
lockJedis.unlock();
}
return jedis;
} /**
* 释放jedis资源
*
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
} /**
* 设置 String
*
* @param key
* @param value
*/
public synchronized static void setString(String key, String value) {
try {
value = StringUtils.isEmpty(value) ? "" : value;
getJedis().set(key, value);
} catch (Exception e) {
logger.error("Set key error : " + e);
}
} /**
* 设置 过期时间
*
* @param key
* @param seconds 以秒为单位
* @param value
*/
public synchronized static void setString(String key, int seconds, String value) {
try {
value = StringUtils.isEmpty(value) ? "" : value;
getJedis().setex(key, seconds, value);
} catch (Exception e) {
logger.error("Set keyex error : " + e);
}
} /**
* 获取String值
*
* @param key
* @return value
*/
public synchronized static String getString(String key) {
if (getJedis() == null || !getJedis().exists(key)) {
return null;
}
return getJedis().get(key);
}
}
synchronized版
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; /**
* Redis 工具类
*/
public class JedisUtil { protected static ReentrantLock lockPool = new ReentrantLock();
protected static ReentrantLock lockJedis = new ReentrantLock(); protected static Logger logger = Logger.getLogger(JedisUtil.class); //Redis服务器IP
private static String ADDR_ARRAY = "xxx.xxx.xxx.xxx"; //Redis的端口号
private static int PORT = 6379; //访问密码
private static String AUTH = "http://blog.csdn.net/unix21";
//可用连接实例的最大数目,默认值为8;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = 8; //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 8; //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = 3000; //超时时间
private static int TIMEOUT = 10000; //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = false; private static JedisPool jedisPool = null; /**
* redis过期时间,以秒为单位
*/
public final static int EXRP_HOUR = 60 * 60; //一小时
public final static int EXRP_DAY = 60 * 60 * 24; //一天
public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一个月 /**
* 初始化Redis连接池
*/
private static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT, AUTH);
} catch (Exception e) {
logger.error("First create JedisPool error : " + e);
try {
//如果第一个IP异常,则访问第二个IP
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT, AUTH);
} catch (Exception e2) {
logger.error("Second create JedisPool error : " + e2);
}
}
} /**
* 在多线程环境同步初始化
*/
private static synchronized void poolInit() {
if (jedisPool == null) {
initialPool();
}
} /**
* 同步获取Jedis实例
* @return Jedis
*/
public synchronized static Jedis getJedis() {
if (jedisPool == null) {
poolInit();
}
Jedis jedis = null;
try {
if (jedisPool != null) {
jedis = jedisPool.getResource();
}
} catch (Exception e) {
logger.error("Get jedis error : "+e);
}finally{
returnResource(jedis);
}
return jedis;
} /**
* 释放jedis资源
*
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null && jedisPool != null) {
jedisPool.returnResource(jedis);
}
} /**
* 设置 String
*
* @param key
* @param value
*/
public synchronized static void setString(String key, String value) {
try {
value = StringUtils.isEmpty(value) ? "" : value;
getJedis().set(key, value);
} catch (Exception e) {
logger.error("Set key error : " + e);
}
} /**
* 设置 过期时间
*
* @param key
* @param seconds 以秒为单位
* @param value
*/
public synchronized static void setString(String key, int seconds, String value) {
try {
value = StringUtils.isEmpty(value) ? "" : value;
getJedis().setex(key, seconds, value);
} catch (Exception e) {
logger.error("Set keyex error : " + e);
}
} /**
* 获取String值
*
* @param key
* @return value
*/
public synchronized static String getString(String key) {
if (getJedis() == null || !getJedis().exists(key)) {
return null;
}
return getJedis().get(key);
}
}
多线程
public class ClientThread extends Thread {
int i = 0;
public ClientThread(int i) {
this.i = i;
}
public void run() {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
JedisUtil.setString("foo", time);
String foo = JedisUtil.getString("foo");
System.out.println("【输出>>>>】foo:" + foo + " 第:"+i+"个线程" +"当前时间:"+DateUtil.getNowTimeString());
}
}
起10000个线程
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
ClientThread t = new ClientThread(i);
t.start();
}
}
在单机4核普通PC机器测试下来10000条数据跑了2秒,性能还是不错的,没有报异常。这种连接池一定要用多线程测试,不然线下没事,线上就会时不时的出问题
memcached和redis的区别:
1. memcached仅支持简单的K/V类型的数据,redis不仅支持K/V类型的数据,同时还提供list,set ,hash等数据结构的存储
2. memcached挂掉后,数据就没了,不可恢复,redis挂掉后,数据可以恢复,通过aof恢复
参考:https://www.cnblogs.com/lcngu/p/6702479.html
Redis的使用及参考代码的更多相关文章
- js页面跳转参考代码大全
整理一下JS页面跳转参考代码 第一种: <script language=/"javascript/" type=/"text/javascript/&qu ...
- Java阶段性测试--第四五六大题参考代码
第四题:.此题要求用IO流完成 使用File类在D盘下创建目录myFiles, 并在myFiles目录下创建三个文件分别为:info1.txt, info2.txt, info3.txt . 代码: ...
- SqlBulkCopy快速插入datatable到数据库中参考代码,以及要注意的问题
参考代码如下: public class Examination { #region 批量插入一个sheet的专业对应的学科 /// <summary> /// 批量插入一个sheet的专 ...
- Redis学习记录及Jedis代码示例
文章目录 二.Redis简介 三.Redis安装 1. 下载并解压安装 2. 安装C语言编译环境 3. 修改安装位置 4. 编译安装 5.启动Redis服务器 ①默认启动 ②定制配置项启动 [1]准备 ...
- yii组态 redis主从配置(随着代码)
最近的欲望redis 主从,但yii内建的redis 它不支持主从.不仅写了一个好办法 结构例,以下: 1.main.php通过添加下面的句子: //redis缓存配置 'cache_redis' = ...
- 芯灵思Sinlinx A64 linux 通过设备树写LED驱动(附参考代码,未测试)
开发平台 芯灵思Sinlinx A64 内存: 1GB 存储: 4GB 详细参数 https://m.tb.cn/h.3wMaSKm 开发板交流群 641395230 全志A64设备树结构体 #inc ...
- 全志A33 linux led驱动编程(附实测参考代码)
开发平台 * 芯灵思SinlinxA33开发板 淘宝店铺: https://sinlinx.taobao.com/ 嵌入式linux 开发板交流 QQ:641395230 开发平台 * 芯灵思Sinl ...
- 阿里云ECS安装的redis服务器,用java代码去连接报错。
import redis.clients.jedis.Jedis; /** * Hello world! * */ public class App { public static void main ...
- 大数据技术之_19_Spark学习_05_Spark GraphX 应用解析 + Spark GraphX 概述、解析 + 计算模式 + Pregel API + 图算法参考代码 + PageRank 实例
第1章 Spark GraphX 概述1.1 什么是 Spark GraphX1.2 弹性分布式属性图1.3 运行图计算程序第2章 Spark GraphX 解析2.1 存储模式2.1.1 图存储模式 ...
随机推荐
- ios下,<input type="checkbox"> 点击时出现黑色块
ios下,<input type="checkbox"> 点击时出现黑色块如下图 解决方法:
- crm开发之用户ModelForm定制和密码加密
写了这么多的定制 功能.终于可以定制一下了!因为是 stark 和 rbac 两个组建. 一起使用. 所以在这里,再记录一下.需要注意的点: 先放出 目录结构: 先从 stark 开始.使用star ...
- JavaSE基础知识(5)—面向对象(5.7 final关键字)
一.说明 final属于一种修饰符,可以用于修饰类和属性.方法.局部变量 二.特点 1.修饰类 该类不能被继承,如String.Integer等 2.修饰方法 该方法不能被重写 3.修饰变量(属性和局 ...
- 利用正则表达式实现python强口令检测
""" Chapter 7 模式匹配和正则表达式 1 用import re 导入正则表达式模块 2 用re.compile()函数创建一个Regex对象(记得使用原始字符 ...
- elementUI表格排序问题
elementUI表格排序: 问题:得不到排序后的数组,每次打印的总是一开始的数据 <el-table ref="passTable" :data="passTab ...
- Python用HTMLTestRunner生成html测试报告
小编的主机:mac 一.引入HTMLTestRunner包 1.下载HTMLTestRunner.py,已上传到网盘,点击下载 2.将HTMLTestRunner.py复制到python安装目录的Li ...
- go语言基本语法
一个例子总结go语言基本语法 demo.go package main import ( "fmt" ) //结构体 type PersonD struct ...
- Python之路(第三十五篇) 并发编程:操作系统的发展史、操作系统的作用
一.操作系统发展史 第一阶段:手工操作 —— 真空管和穿孔卡片 第一代之前人类是想用机械取代人力,第一代计算机的产生是计算机由机械时代进入电子时代的标志,从Babbage失败之后一直到第二次世界大 ...
- n2n网络环境搭建
目的: 实现家中nas,在任何环境ssh访问 方案:n2n v1 (原因稳定&兼容macbook) 开源地址: https://svn.ntop.org/svn/ntop/trunk/n2 ...
- 《Miracle_House》团队项目系统设计改进
一.团队项目系统设计改进: 1.分析项目系统设计说明书初稿的不足,特别是软件系统结构模型建模不完善内容: 对于原文档中,设计图中存在的错误以及文字描述不准确的地方进行了修改. 2. 团队项目Githu ...