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. 2016/3/27 PHP中include和require的区别详解

    1.概要 require()语句的性能与include()相类似,都是包括并运行指定文件.不同之处在于:对include()语句来说,在执行文件时每次都要进行读取和评估:而对于require()来说, ...

  2. H5的localStorage简单存储删除

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  3. HTTP要点概述:三,客户端和服务器,请求和响应

    一,客户端和服务器: HTTP协议主要用于客户端和服务器之间的通信. 1,客户端(client):请求访问资源的一端.(知道为啥用C表示客户端了吧) 2,服务器(server):提供资源响应的一端. ...

  4. SRM691 Sunnygraphs2

    Problem Statement Hero has just constructed a very specific graph. He started with n isolated vertic ...

  5. u-boot支持LCD显示(基于TQ2440)【转】

    本文转载自:http://www.cnblogs.com/pengdonglin137/p/4633877.html u-boot支持LCD显示(基于TQ2440)   阅读目录(Content) 平 ...

  6. YTU 2906: 多重继承 日期与时间

    2906: 多重继承 日期与时间 时间限制: 1 Sec  内存限制: 128 MB 提交: 240  解决: 190 题目描述 在空缺的地方补全代码,只需提交补全部分即可 请用C++方式提交 #in ...

  7. 如何完成DEDE CMS外部数据库调用|不同数据库调用数据

    dedecms如何完成2个数据库内容彼此调用?这是笔者今日要和我们共享的内容.百度了一大堆,大多语焉不详.常识有限,所以就说下笔者的做法, 能够还有其他有用的办法,欢送共享.笔者站点是dedecms5 ...

  8. POJ - 1459 Power Network(最大流)(模板)

    1.看了好久,囧. n个节点,np个源点,nc个汇点,m条边(对应代码中即节点u 到节点v 的最大流量为z) 求所有汇点的最大流. 2.多个源点,多个汇点的最大流. 建立一个超级源点.一个超级汇点,然 ...

  9. I.MX6 ifconfig: SIOCSIFHWADDR: Cannot assign requested address

    /************************************************************************** * I.MX6 ifconfig: SIOCSI ...

  10. centos 7更换阿里源

    转自 https://blog.csdn.net/jameshadoop/article/details/54881295 centos7 修改yum源为阿里源,某下网络下速度比较快 首先是到yum源 ...