Java 使用Jedis操作Redis

Java 使用Jedis操作Redis

    <div class="article_manage clearfix">
    <div class="article_l">
        <span class="link_categories">
        标签:
          <a href="http://www.csdn.net/tag/java" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">java</a><a href="http://www.csdn.net/tag/redis" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">redis</a><a href="http://www.csdn.net/tag/jedis" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">jedis</a>
        </span>
    </div>
    <div class="article_r">
        <span class="link_postdate">2017-09-23 18:44</span>
        <span class="link_view" title="阅读次数">53人阅读</span>
        <span class="link_comments" title="评论次数"> <a href="#comments" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_pinglun'])">评论</a>(0)</span>
        <span class="link_collect tracking-ad" data-mod="popu_171"> <a href="javascript:void(0);" onclick="javascript:collectArticle('Java+%e4%bd%bf%e7%94%a8Jedis%e6%93%8d%e4%bd%9cRedis','78072587');return false;" title="收藏" target="_blank">收藏</a></span>
         <span class="link_report"> <a href="#report" onclick="javascript:report(78072587,2);return false;" title="举报">举报</a></span>

    </div>
</div>    <style type="text/css">        
        .embody{
            padding:10px 10px 10px;
            margin:0 -20px;
            border-bottom:solid 1px #ededed;                
        }
        .embody_b{
            margin:0 ;
            padding:10px 0;
        }
        .embody .embody_t,.embody .embody_c{
            display: inline-block;
            margin-right:10px;
        }
        .embody_t{
            font-size: 12px;
            color:#999;
        }
        .embody_c{
            font-size: 12px;
        }
        .embody_c img,.embody_c em{
            display: inline-block;
            vertical-align: middle;               
        }
         .embody_c img{               
            width:30px;
            height:30px;
        }
        .embody_c em{
            margin: 0 20px 0 10px;
            color:#333;
            font-style: normal;
        }
</style>
<script type="text/javascript">
    $(function () {
        try
        {
            var lib = eval("("+$("#lib").attr("value")+")");
            var html = "";
            if (lib.err == 0) {
                $.each(lib.data, function (i) {
                    var obj = lib.data[i];
                    //html += '<img src="' + obj.logo + '"/>' + obj.name + "&nbsp;&nbsp;";
                    html += ' <a href="' + obj.url + '" target="_blank">';
                    html += ' <img src="' + obj.logo + '">';
                    html += ' <em><b>' + obj.name + '</b></em>';
                    html += ' </a>';
                });
                if (html != "") {
                    setTimeout(function () {
                        $("#lib").html(html);                      
                        $("#embody").show();
                    }, 100);
                }
            }      
        } catch (err)
        { }

    });
</script>
  <div class="category clearfix">
    <div class="category_l">
       <img src="http://static.blog.csdn.net/images/category_icon.jpg">
        <span>分类:</span>
    </div>
    <div class="category_r">
                <label onclick="GetCategoryArticles('6976627','HG_Harvey','top','78072587');">
                    <span onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_fenlei']);">Java<em>(1)</em></span>
                  <img class="arrow-down" src="http://static.blog.csdn.net/images/arrow_triangle _down.jpg" style="display:inline;">
                  <img class="arrow-up" src="http://static.blog.csdn.net/images/arrow_triangle_up.jpg" style="display:none;">
                    <div class="subItem">
                        <div class="subItem_t"><a href="http://blog.csdn.net/HG_Harvey/article/category/6976627" target="_blank">作者同类文章</a><i class="J_close">X</i></div>
                        <ul class="subItem_l" id="top_6976627">                            
                        </ul>
                    </div>
                </label>                    
                <label onclick="GetCategoryArticles('7190559','HG_Harvey','top','78072587');">
                    <span onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_fenlei']);">Redis<em>(4)</em></span>
                  <img class="arrow-down" src="http://static.blog.csdn.net/images/arrow_triangle _down.jpg" style="display:inline;">
                  <img class="arrow-up" src="http://static.blog.csdn.net/images/arrow_triangle_up.jpg" style="display:none;">
                    <div class="subItem">
                        <div class="subItem_t"><a href="http://blog.csdn.net/HG_Harvey/article/category/7190559" target="_blank">作者同类文章</a><i class="J_close">X</i></div>
                        <ul class="subItem_l" id="top_7190559">                            
                        </ul>
                    </div>
                </label>                    
    </div>
</div>
    <div class="bog_copyright">         
        <p class="copyright_p">版权声明:本文为博主原创文章,未经博主允许不得转载。</p>
    </div>

Jedis 是 Redis 官方首选的 Java 客户端开发包
官网地址:https://github.com/xetorthio/jedis
在正式使用jedis之前,需要修改redis.conf文件中的两个参数,开启redis的远程访问,否则无法连接redis
(1).注释掉bing 127.0.0.1,否则只能本机访问
(2).关闭redis的保护模式

官网下载jedis的jar,笔者安装的redis版本为4.0.1,jedis操作redis需要引入jedis-2.9.0.jar,如果想要使用redis的连接池的话,还需要commons-pool2-2.4.1.jar

通过jedis完成对redis存取值的操作,代码如下

package jedistest;

import redis.clients.jedis.Jedis;

/**
 * Jedis 操作 Redis
 */
public class JedisTest {

    private static Jedis jedis;

    public static void main(String[] args) {
        jedis = new Jedis("192.168.242.161", 6379);

        jedis.set("name", "zhangsan");

        String value = jedis.get("name");

        System.out.println("name = " + value);
    }
}
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

输出结果:

name = zhangsan
    
    
  • 1

一般我们不建议通过上面的方式来操作redis,因为每一次jedis操作都要打开一次redis的远程连接,消耗资源,解决方法就是使用连接池,连接池中有三个重要的类,分别如下

JedisPoolConfig:设置和读取配置文件
JedisPool:Jedis连接池
Jedis:Jedis操作对象
    
    
  • 1
  • 2
  • 3

Jedis 操作 Redis 代码如下

package jedistest;

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Jedis 操作 Redis(使用连接池)
 */
public class JedisPoolTest {

    private static int MAX_TOTAL = 20; // 最大连接数,默认为8,-1表示不限制
    private static int MAX_IDLE = 10; // 最大空闲连接数,默认为8
    private static int MIN_IDLE = 5; // 初始化连接数
    private static int MAX_WAIT = 10000; // 最大等待时间,单位为毫秒,默认-1,永不超时,如果超时,抛出异常 JedisConnectionException
    private static boolean TEST_ON_BORROW = true; // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;


    private static String HOST = "192.168.242.161"; // IP
    private static int PORT = 6379; // 端口,默认6379
    private static String AUTH = "admin"; // redis 密码
    private static int TIMEOUT = 1000; // 超时时间

    private static Jedis jedis = null;
    private JedisPool jedisPool = null;

    @Before
    public void init() throws Exception {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(MAX_TOTAL);
        poolConfig.setMaxIdle(MAX_IDLE);
        poolConfig.setMinIdle(MIN_IDLE);
        poolConfig.setMaxWaitMillis(MAX_WAIT);
        poolConfig.setTestOnBorrow(TEST_ON_BORROW);

        // 如果有密码,需要设置
        // JedisPool jedisPool = new JedisPool(poolConfig, HOST, PORT, TIMEOUT, AUTH);

        jedisPool  = new JedisPool(poolConfig, HOST, PORT);

        jedis = jedisPool .getResource();
    }

    // Redis String 字符串
    @Test
    public void testString() throws Exception {
        // set get
        jedis.set("address", "HeBei");
        System.out.println("address = " + jedis.get("address"));

        // append
        jedis.append("address", " tangsan");
        System.out.println("address = " + jedis.get("address"));

        // del
        jedis.del("address");
        System.out.println("address = " + jedis.get("address"));
    }

    // Redis List 列表
    @Test
    public void testList() throws Exception {
        // lpush lrange
         jedis.lpush("dblist", "mysql", "oracle", "db2");
         System.out.println("dblist = " + jedis.lrange("dblist", 0, -1));

        // rpush lrange
        jedis.rpush("dblist", "mongodb", "redis");
        System.out.println("dblist = " + jedis.lrange("dblist", 0, -1));

        // lpop lrange
        jedis.lpop("dblist");
        System.out.println("dblist = " + jedis.lrange("dblist", 0, -1));

        // llen
        System.out.println(jedis.llen("dblist"));
    }

    // Redis Set 无序集合
    @Test
    public void testSet() throws Exception {
        // sadd smembers
        jedis.sadd("myset", "peach", "pear", "banana");
        System.out.println("myset = " + jedis.smembers("myset"));

        // srem smembers
        jedis.srem("myset", "banana");
        System.out.println("myset = " + jedis.smembers("myset"));

        // scard
        System.out.println(jedis.scard("myset"));
    }

    // Redis Hash 哈希
    @Test
    public void testHash() throws Exception {
        // hset
        Map<String, String> hash = new HashMap<String, String>();
        hash.put("name", "tom");
        hash.put("age", "20");
        hash.put("address", "ShangHai");
        jedis.hmset("user", hash);

        // hdel
        jedis.hdel("user", "address");

        // hexists
        System.out.println(jedis.hexists("user", "address"));

        // hkeys 
        Set<String> hkeys = jedis.hkeys("user");
        for (String str : hkeys) {
            System.out.println(str);
        }

        // hvals
        List<String> hvals = jedis.hvals("user");
        for (String str : hvals) {
            System.out.println(str);
        }

        // hgetall
        Map<String, String> map = jedis.hgetAll("user");
        for(Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }

    // Redis ZSet 有序集合
    @Test
    public void testZSet() throws Exception {
        // zadd zrange
        Map<String, Double> scoreMembers = new HashMap<String, Double>();
        scoreMembers.put("math", 90.0);
        scoreMembers.put("english", 87.5);
        scoreMembers.put("sports", 94.0);
        scoreMembers.put("music", 67.0);
        scoreMembers.put("politics", 97.0);
        jedis.zadd("score_set", scoreMembers);
        System.out.println(jedis.zrange("score_set", 0, -1));
        System.out.println(jedis.zrangeWithScores("score_set", 0, -1));

        // zrem 
        jedis.zrem("score_set", "sports");
        System.out.println(jedis.zrange("score_set", 0, -1));

        // zcard
        System.out.println(jedis.zcard("score_set"));

        // zrank
        System.out.println(jedis.zrank("score_set", "math"));
    }

    // Java对象存储到Redis(使用序列化)
    @Test
    public void testSerialize() throws Exception {
        User user = new User(1, "张三", "河北");
        jedis.set("user".getBytes(), SerializeUtil.serialize(user));
    }

    // Redis 反序列化后转为Java对象
    @Test
    public void testDeSerialize() throws Exception {
        byte[] bytes = jedis.get("user".getBytes());
        System.out.println((User)SerializeUtil.deSerialize(bytes));
    }

    // 释放资源
    @After
    public void destory() throws Exception {
        if (jedis != null) {
            jedis.close();
        }
    }
}

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187

User 对象

package jedistest;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    private int id;
    private String name;
    private String address;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public User() {

    }

    public User(int id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", address=" + address + "]";
    }
}

    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

序列化与反序列化工具类

package jedistest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {

    /**
     * 序列化对象
     */
    public static byte[] serialize(Object obj) {
        byte[] bytes = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ;
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            bytes = baos.toByteArray();
            baos.close();
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /**
     * 反序列化对象
     */
    public static Object deSerialize(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值