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基本使用的更多相关文章

  1. java操作redis之jedis篇

    首先来简单介绍一下jedis,其实一句话就可以概括的,就是java操作redis的一种api.我们知道redis提供了基本上所有常用编程语言的clients,大家可以到http://redis.io/ ...

  2. Java连接redis的使用演示样例

    Java连接redis的使用演示样例 Redis是开源的key-value存储工具,redis通经常使用来存储结构化的数据,由于redis的key能够包括String.hash.listset和sor ...

  3. Java的redis 操作类-优化通用版本

    java操作redis多节点处理方式;http://blog.itpub.net/29254281/viewspace-1188644/首先maven引入依赖包 <dependency> ...

  4. redis学习心得之三-【java操作redis】

    今天主要是讲讲java对redis的操作,来段代码掩饰下基本操作即可明白. java调用你需要下载jedis.jar包 下载网址:https://github.com/xetorthio/jedis/ ...

  5. java 操作redis

    使用Java操作Redis需要jedis-2.1.0.jar,如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar package com.test; import ja ...

  6. java操作redis redis连接池

    redis作为缓存型数据库,越来越受到大家的欢迎,这里简单介绍一下java如何操作redis. 1.java连接redis java通过需要jedis的jar包获取Jedis连接. jedis-2.8 ...

  7. java 操作 redis

    1.Java 使用 Redis 只需要下载一个jar包即可 地址:http://maven.outofmemory.cn/redis.clients/jedis/2.5.2/ 工程

  8. java 使用redis 数据库

    [TOC] java 使用redis 数据库 连接redis package com.wsc.redis.Test1; import java.util.List; import java.util. ...

  9. windows下Redis安装及利用java操作Redis

    一.windows下Redis安装 1.Redis下载 下载地址:https://github.com/MicrosoftArchive/redis 打开下载地址后,选择版本 然后选择压缩包 下载 R ...

  10. Java使用Redis实现分布式锁来防止重复提交问题

    如何用消息系统避免分布式事务? - 少年阿宾 - BlogJavahttp://www.blogjava.net/stevenjohn/archive/2018/01/04/433004.html [ ...

随机推荐

  1. Part1-Redefining your data-access strategy 重新定义你的数据访问策略

    欢迎来到Entity Framework 4 In Action,EF是微软3.5 SP1推出的ORM工具,现在已经更新到4.0版本(...)本书能确保你in a  robust and model- ...

  2. qemu所支持的网卡

    1 命令 -net nic 创建一个network interface card,即创建一个网卡,默认是e1000网卡. 2 qemu所支持的网卡类型 2.1 rtl8139 Realtek 10/1 ...

  3. 如何快速定位JVM中消耗CPU最多的线程? Java 性能调优

    https://mp.weixin.qq.com/s/ZqlhPC06_KW6a9OSgEuIVw 上面的线程栈我们注意到 nid 的值其实就是线程 ID,它是十六进制的,我们将消耗 CPU 最高的线 ...

  4. How to use filters in a GridPanel

    You can just link statically required files in your index.html <link rel="stylesheet" t ...

  5. cocos2dx笔记1:概述

    1.核心的类和功能 CCDirector gameLoop,实现场景绘制.多个场景之间切换控制.控制游戏的停止,暂停,等生命周期. CCScene 场景类,每一个场景能够理解为一个游戏镜头.状态 CC ...

  6. JS事件流与DOM事件处理程序

    在Javascript的DOM中,关于事件Event对象的知识是一定要掌握的.Event对象模型主要分为两个部分,一个是Event对象本身具有的属性和方法,这个参照API就可以学得:另一个是在DOM节 ...

  7. 关于ArcGis for javascrept之FeatureLayer类与GraphicsLayer类

    FeatureLayer: ArcGIS for Server发布的要素服务或者地图服务中的图层 构造方法: myFeatureLayer = new esri.layers.FeatureLayer ...

  8. MFC优秀博客记录 鸡啄米

    最近在学习和利用C++ MFC做一些小的应用,发现鸡啄米先生的教程很不错适合新手,在这就把自己实现的一些小demo分享一下: C++编程入门系列之目录和总结 第一部分:C++编程概述 第二部分:C++ ...

  9. WordPress xmlrpc.php flaw exploited to install a WSO 2.1 Web Shell by oRb

    WordPress xmlrpc.php flaw exploited to install a “WSO 2.1 Web Shell by oRb” Below you can see in the ...

  10. 记bugku的——“welcome to bugkuctf”

    今天终于拾起来ctf的比赛了,开始了练习之旅.今天写一道bugku上的题目wp,属于利用php源码泄漏的题目吧,我觉得不是很简单...所以把自己的思路放上来. 题目源头:http://120.24.8 ...