1 引入jar包

  java是通过Jedis对redis进行操作的,首先引入jedis.jar

  <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
  </dependency>

2 建立redis连接池

  

  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. import redis.clients.jedis.Jedis;
  5. import redis.clients.jedis.JedisPool;
  6. import redis.clients.jedis.JedisPoolConfig;
  7. import redis.clients.jedis.JedisShardInfo;
  8. import redis.clients.jedis.ShardedJedis;
  9. import redis.clients.jedis.ShardedJedisPool;
  10.  
  11. public class RedisPool {
  12.  
  13. // 非切片客户端链接对象
  14. private Jedis jedis;
  15. // 非切片链接池对象
  16. private JedisPool jedisPool;
  17. // 切片客户端链接对象
  18. private ShardedJedis shardedJedis;
  19. // 切片链接池
  20. private ShardedJedisPool shardedJedisPool;
  21.  
  22. private String ip = "127.0.0.1";
  23. private int port = 6379;
  24.  
  25. public RedisPool(){
  26. initializePool();
  27. initializeShardedPool();
  28. setJedis(jedisPool.getResource());
  29. setShardedJedis(shardedJedisPool.getResource());
  30. }
  31.  
  32. public RedisPool(String ip){
  33. this.ip = ip;
  34. initializePool();
  35. initializeShardedPool();
  36. setJedis(jedisPool.getResource());
  37. setShardedJedis(shardedJedisPool.getResource());
  38. }
  39.  
  40. public RedisPool(String ip, int port){
  41. this.ip = ip;
  42. this.port = port;
  43. initializePool();
  44. initializeShardedPool();
  45. setJedis(jedisPool.getResource());
  46. setShardedJedis(shardedJedisPool.getResource());
  47.  
  48. }
  49.  
  50. // 初始化非切片池
  51. public void initializePool(){
  52. //池的配置
  53. JedisPoolConfig jpc = new JedisPoolConfig();
  54. //最大空闲连接数
  55. jpc.setMaxIdle(20);
  56. jpc.setMaxIdle(5);
  57. //获取连接时的最大等待毫秒数
  58. jpc.setMaxWaitMillis(1000);
  59. //在空闲时检查有效性, 默认false
  60. jpc.setTestOnBorrow(false);
  61. jedisPool = new JedisPool(jpc, ip, port);
  62. }
  63.  
  64. // 初始化切片池
  65. public void initializeShardedPool(){
  66. //池的配置
  67. JedisPoolConfig config = new JedisPoolConfig();
  68. config.setMaxIdle(20);
  69. config.setMaxWaitMillis(1000);
  70. config.setTestOnBorrow(false);
  71. // slave链接
  72. //可以实现集群的功能,配置多个redis服务实现请求的分配进行负载均衡
  73. List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
  74. shards.add(new JedisShardInfo(ip, port, "master"));
  75. // 构造池
  76. shardedJedisPool = new ShardedJedisPool(config, shards);
  77. }
  78.  
  79. public void closeJedisPool(){
  80. jedisPool.close();
  81. }
  82. public void closeShardedJedisPool(){
  83. shardedJedisPool.close();
  84. }
  85.  
  86. public Jedis getJedis() {
  87. return jedis;
  88. }
  89.  
  90. public void setJedis(Jedis jedis) {
  91. this.jedis = jedis;
  92. }
  93.  
  94. public ShardedJedis getShardedJedis() {
  95. return shardedJedis;
  96. }
  97.  
  98. public void setShardedJedis(ShardedJedis shardedJedis) {
  99. this.shardedJedis = shardedJedis;
  100. }
  101. }

  

3 定义操作接口

  

  1. import java.util.Map;
  2. import java.util.Set;
  3.  
  4. public interface IRedisService {
  5.  
  6. public Boolean setString(String key, String value);
  7. public String getString(String key);
  8. public Boolean existsKey(String key);
  9. public Long delKey(String key);
  10. public String typeKey(String key);
  11. public Set<String> keys(String key);
  12.  
  13. /**
  14. * 获得map数据集
  15. * @param key
  16. * @return
  17. */
  18. public Map<String, String> getMap(String key);
  19.  
  20. /**
  21. * 设置map数据集
  22. * @param key
  23. * @param map
  24. * @return
  25. */
  26. public Boolean setMap(String key, Map<String, String> map);
  27.  
  28. /**
  29. * 获得map字段中的值
  30. * @param key
  31. * @param fieldKey
  32. * @return
  33. */
  34. public String getMapFieldValue(String key, String fieldKey);
  35.  
  36. /**
  37. * 获得map中多个字段值
  38. * @param key
  39. * @param fieldKeys
  40. * @return
  41. */
  42. public Map<String, String> getMapFieldValues(String key, String[] fieldKeys);
  43.  
  44. /**
  45. * 设置map中具体的字段值
  46. * 参考存储格式:{key,map{fieldKey, fieldValue}}
  47. * @param key
  48. * @param fieldKey
  49. * @param fieldValue
  50. * @return
  51. */
  52. public Boolean setMapFieldValue(String key, String fieldKey, String fieldValue);
  53.  
  54. }

  

4 接口实现类

  

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.Set;
  4.  
  5. import com.robert.redis.client.config.RedisPool;
  6.  
  7. import redis.clients.jedis.Jedis;
  8. import redis.clients.jedis.ShardedJedis;
  9.  
  10. public class RedisService implements IRedisService{
  11.  
  12. private RedisPool redisPool;
  13.  
  14. public RedisService(){
  15. redisPool = new RedisPool();
  16. }
  17.  
  18. public RedisService(String host){
  19. redisPool = new RedisPool(host);
  20. }
  21.  
  22. public RedisService(String host, int port){
  23. redisPool = new RedisPool(host, port);
  24. }
  25.  
  26. private Jedis getJResource(){
  27. Jedis jResource = null;
  28. jResource = redisPool.getJedis();
  29. return jResource;
  30. }
  31. private ShardedJedis getShardResource(){
  32. ShardedJedis sResource = null;
  33. sResource = redisPool.getShardedJedis();
  34. return sResource;
  35. }
  36.  
  37. public Boolean setString(String key, String value) {
  38. boolean result = false;
  39. ShardedJedis resource = null;
  40. try{
  41. resource = getShardResource();
  42. if(resource != null){
  43. resource.set(key, value);
  44. result = true;
  45. }
  46.  
  47. }catch(Exception e){
  48. result = false;
  49. e.printStackTrace();
  50. }finally{
  51. redisPool.closeShardedJedisPool();
  52. }
  53. return result;
  54. }
  55.  
  56. public String getString(String key) {
  57. String result = null;
  58. ShardedJedis resource = null;
  59. try{
  60. resource = getShardResource();
  61. if(resource != null){
  62. result = resource.get(key);
  63. }
  64.  
  65. }catch(Exception e){
  66. result = null;
  67. e.printStackTrace();
  68. }finally{
  69. redisPool.closeShardedJedisPool();
  70. }
  71. return result;
  72. }
  73.  
  74. public Boolean existsKey(String key) {
  75. Boolean result = false;
  76. ShardedJedis resource = null;
  77. try{
  78. resource = getShardResource();
  79. if(resource != null){
  80. result = resource.exists(key);
  81. }
  82. }catch(Exception e){
  83. e.printStackTrace();
  84. }finally{
  85. redisPool.closeShardedJedisPool();
  86. }
  87.  
  88. return result;
  89. }
  90.  
  91. public Long delKey(String key) {
  92. Long result = null;
  93. ShardedJedis resource = null;
  94. try{
  95. resource = getShardResource();
  96. if(resource != null){
  97. result = resource.del(key);
  98. }
  99. }catch(Exception e){
  100. e.printStackTrace();
  101. }finally{
  102. redisPool.closeShardedJedisPool();
  103. }
  104. return result;
  105. }
  106.  
  107. public String typeKey(String key) {
  108. String result = null;
  109. ShardedJedis resource = null;
  110. try{
  111. resource = getShardResource();
  112. if(resource != null){
  113. result = resource.type(key);
  114. }
  115. }catch(Exception e){
  116. e.printStackTrace();
  117. }finally{
  118. redisPool.closeShardedJedisPool();
  119. }
  120. return result;
  121. }
  122.  
  123. public Set<String> keys(String key) {
  124. Set<String> result = null;
  125. Jedis resource = null;
  126. try{
  127. resource = getJResource();
  128. if(resource != null){
  129. result = resource.keys(key);
  130. }
  131.  
  132. }catch(Exception e){
  133. result = null;
  134. e.printStackTrace();
  135. }finally{
  136. redisPool.closeJedisPool();
  137. }
  138. return result;
  139. }
  140.  
  141. public Map<String, String> getMap(String key) {
  142. Map<String, String> map = null;
  143. ShardedJedis resource = null;
  144. try{
  145. resource = getShardResource();
  146. if(resource != null && resource.exists(key)){
  147. map = resource.hgetAll(key);
  148. }
  149. }catch(Exception e){
  150. e.printStackTrace();
  151. }finally{
  152. redisPool.closeShardedJedisPool();
  153. }
  154. return map;
  155. }
  156.  
  157. public Boolean setMap(String key, Map<String, String> map) {
  158. Boolean result = false;
  159. ShardedJedis resource = null;
  160. try{
  161. resource = getShardResource();
  162. if(resource != null){
  163. resource.hmset(key, map);
  164. result = true;
  165. }
  166. }catch(Exception e){
  167. e.printStackTrace();
  168. }finally{
  169. redisPool.closeShardedJedisPool();
  170. }
  171. return result;
  172. }
  173.  
  174. public String getMapFieldValue(String key, String fieldKey) {
  175. String result = null;
  176. ShardedJedis resource = null;
  177. try{
  178. resource = getShardResource();
  179. if(resource != null && resource.hexists(key, fieldKey)){
  180. result = resource.hget(key, fieldKey);
  181. }
  182. }catch(Exception e){
  183. e.printStackTrace();
  184. }finally{
  185. redisPool.closeShardedJedisPool();
  186. }
  187. return result;
  188. }
  189.  
  190. public Map<String, String> getMapFieldValues(String key, String[] fieldKeys) {
  191. Map<String, String> map = new HashMap<String, String>();
  192. ShardedJedis resource = null;
  193. try{
  194. resource = getShardResource();
  195. if(resource != null){
  196. for(String fieldKey : fieldKeys){
  197. map.put(fieldKey, resource.hget(key, fieldKey));
  198. }
  199. }
  200. }catch(Exception e){
  201. e.printStackTrace();
  202. }finally{
  203. redisPool.closeShardedJedisPool();
  204. }
  205. return map;
  206. }
  207.  
  208. public Boolean setMapFieldValue(String key, String fieldKey, String fieldValue) {
  209. Boolean result = false;
  210. ShardedJedis resource = null;
  211. try{
  212. resource = getShardResource();
  213. if(resource != null && resource.exists(key)){
  214. resource.hset(key, fieldKey, fieldValue);
  215. result = true;
  216. }
  217. }catch(Exception e){
  218. e.printStackTrace();
  219. }finally{
  220. redisPool.closeShardedJedisPool();
  221. }
  222. return result;
  223. }
  224.  
  225. }

  

5 测试

  

  1. public static void main( String[] args )
  2. {
  3.  
  4. IRedisService rs = new RedisService();
  5. rs.setString("test", "Hello Redis!");
  6. System.out.println(rs.getString("test"));
  7. }

  

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. java语法基础(四)

    继承 继承概述 继承是面向对象语言的三大基本特性(封装,继承,多态)之一. 一个类可以继承另外一个类,继承的类称为子类(也可以叫派生类),被继承的类称为父类(或者也叫基类,超类). 通过继承,子类可以 ...

  2. iOS 7 present/dismiss转场动画

    前言 iOS 7以后提供了自定义转场动画的功能,我们可以通过遵守协议完成自定义转场动画.本篇文章讲解如何实现自定义present.dismiss自定义动画. 效果图 本篇文章实现的动画切换效果图如下: ...

  3. 【FFT初识】

      FFT在用于解决多项式乘法A*B(A和B为多项式,形如a0+a1*x^1+a2*x^2....)的时候,通俗地解释就是: 原理:先根据各自的系数各自转化为对应的向量(O(nlogn)),然后向量相 ...

  4. ChartCtrl源码剖析之——CChartAxisLabel类

    CChartAxisLabel类用来绘制轴标签,上.下.左.右都可以根据实际需要设置对应的轴标签.它处于该控件的区域,如下图所示: CChartAxisLabel类的头文件. #if !defined ...

  5. bzoj 1923: [Sdoi2010]外星千足虫【高斯消元】

    裸的异或高斯消元 #include<iostream> #include<cstdio> using namespace std; const int N=2005; int ...

  6. Luogu P2735 电网【真·计算几何/Pick定理】By cellur925

    题目传送门 刷USACO偶然遇到的,可能是人生中第一道正儿八经的计算几何. 题目大意:在平面直角坐标系中给你一个以格点为顶点的三角形,求三角形中的整点个数. 因为必修5和必修2的阴影很快就想到了数学中 ...

  7. Golang 在 Linux CentOS 6.5 服务器上实现 博客后台程序开机启动

    在linux下想实现开机启动的方法很多,这里我采用了在/etc/rc.local里写shell指令的方式. 以下就以我的实际操作为例子讲述,很多地方需要看官自己调整信息哦! 1.在/etc/rc.lo ...

  8. Manven下载

        1.下载地址:http://maven.apache.org/download.cgi          2.点击下载链接          3.解压zip到安装路径  我的:C:\Progr ...

  9. [BZOJ3531] Peaks加强版

    Peaks Peaks 加强版 Description 在Bytemountains有N座山峰,每座山峰有他的高度h_i.有些山峰之间有双向道路相连,共M条路径,每条路径有一个困难值,这个值越大表示越 ...

  10. 排序sort与qsort

    首先看sort函数见下表: 函数名 功能描述 sort 对给定区间所有元素进行排序 stable_sort 对给定区间所有元素进行稳定排序 partial_sort 对给定区间所有元素部分排序 par ...