Java对Redis基本使用
1 引入jar包
java是通过Jedis对redis进行操作的,首先引入jedis.jar
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2 建立redis连接池
import java.util.ArrayList;
import java.util.List; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool; public class RedisPool { // 非切片客户端链接对象
private Jedis jedis;
// 非切片链接池对象
private JedisPool jedisPool;
// 切片客户端链接对象
private ShardedJedis shardedJedis;
// 切片链接池
private ShardedJedisPool shardedJedisPool; private String ip = "127.0.0.1";
private int port = 6379; public RedisPool(){
initializePool();
initializeShardedPool();
setJedis(jedisPool.getResource());
setShardedJedis(shardedJedisPool.getResource());
} public RedisPool(String ip){
this.ip = ip;
initializePool();
initializeShardedPool();
setJedis(jedisPool.getResource());
setShardedJedis(shardedJedisPool.getResource());
} public RedisPool(String ip, int port){
this.ip = ip;
this.port = port;
initializePool();
initializeShardedPool();
setJedis(jedisPool.getResource());
setShardedJedis(shardedJedisPool.getResource()); } // 初始化非切片池
public void initializePool(){
//池的配置
JedisPoolConfig jpc = new JedisPoolConfig();
//最大空闲连接数
jpc.setMaxIdle(20);
jpc.setMaxIdle(5);
//获取连接时的最大等待毫秒数
jpc.setMaxWaitMillis(1000);
//在空闲时检查有效性, 默认false
jpc.setTestOnBorrow(false);
jedisPool = new JedisPool(jpc, ip, port);
} // 初始化切片池
public void initializeShardedPool(){
//池的配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(20);
config.setMaxWaitMillis(1000);
config.setTestOnBorrow(false);
// slave链接
//可以实现集群的功能,配置多个redis服务实现请求的分配进行负载均衡
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(ip, port, "master"));
// 构造池
shardedJedisPool = new ShardedJedisPool(config, shards);
} public void closeJedisPool(){
jedisPool.close();
}
public void closeShardedJedisPool(){
shardedJedisPool.close();
} public Jedis getJedis() {
return jedis;
} public void setJedis(Jedis jedis) {
this.jedis = jedis;
} public ShardedJedis getShardedJedis() {
return shardedJedis;
} public void setShardedJedis(ShardedJedis shardedJedis) {
this.shardedJedis = shardedJedis;
}
}
3 定义操作接口
import java.util.Map;
import java.util.Set; public interface IRedisService { public Boolean setString(String key, String value);
public String getString(String key);
public Boolean existsKey(String key);
public Long delKey(String key);
public String typeKey(String key);
public Set<String> keys(String key); /**
* 获得map数据集
* @param key
* @return
*/
public Map<String, String> getMap(String key); /**
* 设置map数据集
* @param key
* @param map
* @return
*/
public Boolean setMap(String key, Map<String, String> map); /**
* 获得map字段中的值
* @param key
* @param fieldKey
* @return
*/
public String getMapFieldValue(String key, String fieldKey); /**
* 获得map中多个字段值
* @param key
* @param fieldKeys
* @return
*/
public Map<String, String> getMapFieldValues(String key, String[] fieldKeys); /**
* 设置map中具体的字段值
* 参考存储格式:{key,map{fieldKey, fieldValue}}
* @param key
* @param fieldKey
* @param fieldValue
* @return
*/
public Boolean setMapFieldValue(String key, String fieldKey, String fieldValue); }
4 接口实现类
import java.util.HashMap;
import java.util.Map;
import java.util.Set; import com.robert.redis.client.config.RedisPool; import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis; public class RedisService implements IRedisService{ private RedisPool redisPool; public RedisService(){
redisPool = new RedisPool();
} public RedisService(String host){
redisPool = new RedisPool(host);
} public RedisService(String host, int port){
redisPool = new RedisPool(host, port);
} private Jedis getJResource(){
Jedis jResource = null;
jResource = redisPool.getJedis();
return jResource;
}
private ShardedJedis getShardResource(){
ShardedJedis sResource = null;
sResource = redisPool.getShardedJedis();
return sResource;
} public Boolean setString(String key, String value) {
boolean result = false;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
resource.set(key, value);
result = true;
} }catch(Exception e){
result = false;
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public String getString(String key) {
String result = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
result = resource.get(key);
} }catch(Exception e){
result = null;
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public Boolean existsKey(String key) {
Boolean result = false;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
result = resource.exists(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
} return result;
} public Long delKey(String key) {
Long result = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
result = resource.del(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public String typeKey(String key) {
String result = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
result = resource.type(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public Set<String> keys(String key) {
Set<String> result = null;
Jedis resource = null;
try{
resource = getJResource();
if(resource != null){
result = resource.keys(key);
} }catch(Exception e){
result = null;
e.printStackTrace();
}finally{
redisPool.closeJedisPool();
}
return result;
} public Map<String, String> getMap(String key) {
Map<String, String> map = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null && resource.exists(key)){
map = resource.hgetAll(key);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return map;
} public Boolean setMap(String key, Map<String, String> map) {
Boolean result = false;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
resource.hmset(key, map);
result = true;
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public String getMapFieldValue(String key, String fieldKey) {
String result = null;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null && resource.hexists(key, fieldKey)){
result = resource.hget(key, fieldKey);
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} public Map<String, String> getMapFieldValues(String key, String[] fieldKeys) {
Map<String, String> map = new HashMap<String, String>();
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null){
for(String fieldKey : fieldKeys){
map.put(fieldKey, resource.hget(key, fieldKey));
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return map;
} public Boolean setMapFieldValue(String key, String fieldKey, String fieldValue) {
Boolean result = false;
ShardedJedis resource = null;
try{
resource = getShardResource();
if(resource != null && resource.exists(key)){
resource.hset(key, fieldKey, fieldValue);
result = true;
}
}catch(Exception e){
e.printStackTrace();
}finally{
redisPool.closeShardedJedisPool();
}
return result;
} }
5 测试
public static void main( String[] args )
{ IRedisService rs = new RedisService();
rs.setString("test", "Hello Redis!");
System.out.println(rs.getString("test"));
}
Java对Redis基本使用的更多相关文章
- java操作redis之jedis篇
首先来简单介绍一下jedis,其实一句话就可以概括的,就是java操作redis的一种api.我们知道redis提供了基本上所有常用编程语言的clients,大家可以到http://redis.io/ ...
- Java连接redis的使用演示样例
Java连接redis的使用演示样例 Redis是开源的key-value存储工具,redis通经常使用来存储结构化的数据,由于redis的key能够包括String.hash.listset和sor ...
- Java的redis 操作类-优化通用版本
java操作redis多节点处理方式;http://blog.itpub.net/29254281/viewspace-1188644/首先maven引入依赖包 <dependency> ...
- redis学习心得之三-【java操作redis】
今天主要是讲讲java对redis的操作,来段代码掩饰下基本操作即可明白. java调用你需要下载jedis.jar包 下载网址:https://github.com/xetorthio/jedis/ ...
- java 操作redis
使用Java操作Redis需要jedis-2.1.0.jar,如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar package com.test; import ja ...
- java操作redis redis连接池
redis作为缓存型数据库,越来越受到大家的欢迎,这里简单介绍一下java如何操作redis. 1.java连接redis java通过需要jedis的jar包获取Jedis连接. jedis-2.8 ...
- java 操作 redis
1.Java 使用 Redis 只需要下载一个jar包即可 地址:http://maven.outofmemory.cn/redis.clients/jedis/2.5.2/ 工程
- java 使用redis 数据库
[TOC] java 使用redis 数据库 连接redis package com.wsc.redis.Test1; import java.util.List; import java.util. ...
- windows下Redis安装及利用java操作Redis
一.windows下Redis安装 1.Redis下载 下载地址:https://github.com/MicrosoftArchive/redis 打开下载地址后,选择版本 然后选择压缩包 下载 R ...
- Java使用Redis实现分布式锁来防止重复提交问题
如何用消息系统避免分布式事务? - 少年阿宾 - BlogJavahttp://www.blogjava.net/stevenjohn/archive/2018/01/04/433004.html [ ...
随机推荐
- Linux 对比 Windows 缺点
SELinux_百度百科 https://baike.baidu.com/item/SELinux/8865268?fr=aladdin 虽然Linux比起 Windows来说,它的可靠性,稳 ...
- [m() for i in range(8)]
import time def m(): print(time.time()) time.sleep(1) [m() for i in range(8)] 一行 list
- UPDATE command denied DELETE
可用磁盘空间不足 支持SELECT information_schema. TABLES
- 百度面试经历_web前端开发
百度面试经历_web前端开发 --2016年09月24日校招杭州站 刚面试完,担心过去就忘记掉,故回来时在地铁上用手机码下面试题目,供参考,也留作自己以后的面试参考依据.
- Dynamics CRM 修改Excel 最大导出记录限制及 最大上传文件限制
CRM默认的Excel最大导出记录是10000条,最大上传文件限制为5m. 这样的限制可以满足少量数据的批量更新,但是如果数据量比较大的话需要修改最大的导出记录限制,和上传文件的大小,网上有的是直接修 ...
- HDU1054 Strategic Game —— 最小点覆盖 or 树形DP
题目链接:https://vjudge.net/problem/HDU-1054 Strategic Game Time Limit: 20000/10000 MS (Java/Others) ...
- YTU 2946: 填空:间接基类就是A
2946: 填空:间接基类就是A 时间限制: 1 Sec 内存限制: 128 MB 提交: 132 解决: 96 题目描述 如下程序所示,D继承自B和C,而B和C均继承自A.根据继承的机制,D的对 ...
- ios app 上架AppStore
一.证书的导出 1.1 前期工作 首先你需要有一个苹果的开发者帐号,一个Mac系统. 如果没有帐号可以在打开http://developer.apple.com/ ...
- sql 指删除表,改表名,改字段名
删除表: DECLARE @Table NVARCHAR(30) DECLARE tmpCur CURSOR FOR SELECT name FROM sys.objects WHERE TYPE=' ...
- os.path.dirname(__file__)和os.path.abspath(__file__)区别