Java API 操作Redis

针对Redis的Java客户端有很多种,具体查看官网信息:https://redis.io/clients#java
本次测试使用Jedis API,Jedis使用方便,其api方法名称与redis命令名称一致。
如果不熟悉redis命令,可以参考:《Redis客户端基本命令》

一、依赖

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

二、编码

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisTest {

    private static final String URL = "192.168.2.11";

    private static final int PORT = 6379;

    /**
     * redis简单操作
     */
    @Test
    public void testJedisPool() {
        // 单例
        JedisPool pool = new JedisPool(URL, PORT);
        Jedis jedis = pool.getResource();
        jedis.set("username", "admin");
        String value = jedis.get("username");
        System.out.println(value);
        jedis.close();
    }

    /**
     * redis带config配置操作
     */
    @Test
    public void testJedisPoolAndConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(10);
        config.setMinIdle(5);

        JedisPool pool = new JedisPool(config, URL, PORT);
        Jedis jedis = pool.getResource();
        jedis.set("goods", "手提电脑");
        String value = jedis.get("goods");
        System.out.println(value);
        jedis.close();
    }

    /**
     * redis集群操作
     */
    @Test
    public void testJedisCluster() {
        Set<HostAndPort> nodes = new HashSet<>();
        nodes.add(new HostAndPort(URL, 6379));
        nodes.add(new HostAndPort(URL, 6380));
        nodes.add(new HostAndPort(URL, 6381));
        nodes.add(new HostAndPort(URL, 6382));
        nodes.add(new HostAndPort(URL, 6383));
        nodes.add(new HostAndPort(URL, 6384));
        // 单例
        JedisCluster cluster = new JedisCluster(nodes);
        cluster.set("cluster", "hello world");
        String value = cluster.get("cluster");
        System.out.println(value);
        try {
            // 当系统关闭时才关闭
            cluster.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
posted @ 2017-08-23 18:39  关小西  阅读(1253)  评论(0编辑  收藏  举报