Java操作redis

Posted oneqhw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java操作redis相关的知识,希望对你有一定的参考价值。

Redis作为服务器缓存,用处比较多。本文使用java操作redis,对操作进行简单的封装,并介绍如何将其集成到spring中,最后介绍redis分页查询。

首先定义操作接口,为redis的单机操作和集群操作提供标准。

public interface JedisClient
{
    void set(String key, String value);

    String get(String key);

    void hset(String hkey, String key, String value);

    String hget(String hkey, String key);

    long incr(String key);

    void expire(String key, int seconds);

    long ttl(String key);

    long del(String key);

    long hdel(String hkey, String key);

    /**
     * redis list操作
     * 
     * @param name
     * @param value
     */
    long rpush(String key, String value);

    long lpush(String key, String value);

    String rpop(String key);

    String lpop(String key);

    long llen(String key);

    List<String> lrange(String key, long start, long end);
    
    long zadd(String key, double score, String value);
    
    Set<String> zrange(String key, long start, long end);//递增
    
    Set<String> zrevrange(String key, long start, long end);//递减
}

定义单机版实现类

public class JedisClientSingle implements JedisClient
{
    // 注意,JedisPool这个类型已经在spring中注册过了。这种方式直根据类型来注入
    @Autowired
    private JedisPool jedisPool;

    @Override
    public void set(String key, String value)
    {
        Jedis jedis = jedisPool.getResource();
        jedis.set(key, value);
        jedis.close();
    }

    @Override
    public String get(String key)
    {
        Jedis jedis = jedisPool.getResource();
        String value = jedis.get(key);
        jedis.close();
        return value;
    }

    @Override
    public void hset(String hkey, String key, String value)
    {
        Jedis jedis = jedisPool.getResource();
        jedis.hset(hkey, key, value);
        jedis.close();
    }

    @Override
    public String hget(String hkey, String key)
    {
        Jedis jedis = jedisPool.getResource();
        String value = jedis.hget(hkey, key);
        jedis.close();
        return value;
    }

    @Override
    public long incr(String key)
    {
        Jedis jedis = jedisPool.getResource();
        long value = jedis.incr(key);
        jedis.close();
        return value;
    }

    @Override
    public void expire(String key, int seconds)
    {
        Jedis jedis = jedisPool.getResource();
        jedis.expire(key, seconds);
        jedis.close();
    }

    @Override
    public long ttl(String key)
    {
        Jedis jedis = jedisPool.getResource();
        long value = jedis.ttl(key);
        jedis.close();
        return value;
    }

    @Override
    public long del(String key)
    {
        Jedis jedis = jedisPool.getResource();
        long result = jedis.del(key);
        jedis.close();
        return result;
    }

    @Override
    public long hdel(String hkey, String key)
    {
        Jedis jedis = jedisPool.getResource();
        long result = jedis.hdel(hkey, key);
        jedis.close();
        return result;
    }

    @Override
    public long rpush(String key, String value)
    {
        Jedis jedis = jedisPool.getResource();
        long result = jedis.rpush(key, value);
        jedis.close();
        return result;
    }

    @Override
    public long lpush(String key, String value)
    {
        Jedis jedis = jedisPool.getResource();
        long result = jedis.lpush(key, value);
        jedis.close();
        return result;
    }

    @Override
    public String rpop(String key)
    {
        Jedis jedis = jedisPool.getResource();
        String result = jedis.rpop(key);
        jedis.close();
        return result;
    }

    @Override
    public String lpop(String key)
    {
        Jedis jedis = jedisPool.getResource();
        String result = jedis.lpop(key);
        jedis.close();
        return result;
    }

    @Override
    public long llen(String key)
    {
        Jedis jedis = jedisPool.getResource();
        long result = jedis.llen(key);
        jedis.close();
        return result;
    }

    @Override
    public List<String> lrange(String key, long start, long end)
    {
        Jedis jedis = jedisPool.getResource();
        List<String> result = jedis.lrange(key, start, end);
        jedis.close();
        return result;
    }

    @Override
    public long zadd(String key, double score, String value)
    {
        Jedis jedis = jedisPool.getResource();
        long result = jedis.zadd(key, score, value);
        jedis.close();
        return result;
    }

    @Override
    public Set<String> zrange(String key, long start, long end)
    {
        Jedis jedis = jedisPool.getResource();
        Set<String> result = jedis.zrange(key, start, end);
        jedis.close();
        return result;
    }

    @Override
    public Set<String> zrevrange(String key, long start, long end)
    {
        Jedis jedis = jedisPool.getResource();
        Set<String> result = jedis.zrevrange(key, start, end);
        jedis.close();
        return result;
    }

}

如下是集群操作实现类

public class JedisClientCluster implements JedisClient
{
	// 注意,jedisCluster这个类型已经在spring中注册过了。这种方式直接根据类型来注入,不需要进行关闭操作
	@Autowired
	private JedisCluster jedisCluster;

	@Override
	public void set(String key, String value)
	{
		jedisCluster.set(key, value);
	}

	@Override
	public String get(String key)
	{
		return jedisCluster.get(key);
	}

	@Override
	public void hset(String hkey, String key, String value)
	{
		jedisCluster.hset(hkey, key, value);
	}

	@Override
	public String hget(String hkey, String key)
	{
		return jedisCluster.hget(hkey, key);
	}

	@Override
	public long incr(String key)
	{
		return jedisCluster.incr(key);
	}

	@Override
	public void expire(String key, int seconds)
	{
		jedisCluster.expire(key, seconds);
	}

	@Override
	public long ttl(String key)
	{
		return jedisCluster.ttl(key);
	}

	@Override
	public long del(String key)
	{
		return jedisCluster.del(key);
	}

	@Override
	public long hdel(String hkey, String key)
	{
		return jedisCluster.hdel(hkey, key);
	}

	@Override
	public long rpush(String key, String value)
	{
		return jedisCluster.rpush(key, value);
	}

	@Override
	public long lpush(String key, String value)
	{
		return jedisCluster.lpush(key, value);
	}

	@Override
	public String rpop(String key)
	{
		return jedisCluster.rpop(key);
	}

	@Override
	public String lpop(String key)
	{
		return jedisCluster.lpop(key);
	}

	@Override
	public long llen(String key)
	{
		return jedisCluster.llen(key);
	}

	@Override
	public List<String> lrange(String key, long start, long end)
	{
		return jedisCluster.lrange(key, start, end);
	}

	@Override
	public long zadd(String key, double score, String value)
	{
		return jedisCluster.zadd(key, score, value);
	}

	@Override
	public Set<String> zrange(String key, long start, long end)
	{
		return jedisCluster.zrange(key, start, end);
	}

	@Override
	public Set<String> zrevrange(String key, long start, long end)
	{
		return jedisCluster.zrange(key, start, end);
	}

}

  

jedis相关的bean在spring中的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!-- <property name="maxIdle" value="300" /> --> <!-- 最大能够保持idel状态的对象数 -->
        <!-- <property name="maxTotal" value="60000" />  --><!-- 最大分配的对象数 -->
        <!-- <property name="testOnBorrow" value="true" /> --> <!-- 当调用borrow Object方法时,是否进行有效性检查 -->
    </bean>
    <!-- jedis客户端单机版,开发的时候,都是用单机版 -->
    <bean id="redisClientSingle" class="redis.clients.jedis.JedisPool">
        <constructor-arg name="poolConfig" ref="jedisPoolConfig" />
        <constructor-arg name="host" value="192.168.1.1"></constructor-arg>
        <constructor-arg name="port" value="6379"></constructor-arg>
        <constructor-arg name="timeout" value="2000" type="int"></constructor-arg>
        <constructor-arg name="password" value="xxx"></constructor-arg>
    </bean>

    <bean id="jedisClientSingle" class="org.redis.impl.JedisClientSingle"></bean>

    <!-- jedis客户端集群版,生产环境使用 -->
    <!-- <bean id="redisClientCluster" class="redis.clients.jedis.JedisCluster"> 
        <constructor-arg name="nodes"> <set> <bean class="redis.clients.jedis.HostAndPort"> 
        <constructor-arg name="host" value="192.168.25.128"></constructor-arg> <constructor-arg 
        name="port" value="7001"></constructor-arg> </bean> <bean class="redis.clients.jedis.HostAndPort"> 
        <constructor-arg name="host" value="192.168.25.128"></constructor-arg> <constructor-arg 
        name="port" value="7002"></constructor-arg> </bean> <bean class="redis.clients.jedis.HostAndPort"> 
        <constructor-arg name="host" value="192.168.25.128"></constructor-arg> <constructor-arg 
        name="port" value="7003"></constructor-arg> </bean> <bean class="redis.clients.jedis.HostAndPort"> 
        <constructor-arg name="host" value="192.168.25.128"></constructor-arg> <constructor-arg 
        name="port" value="7004"></constructor-arg> </bean> <bean class="redis.clients.jedis.HostAndPort"> 
        <constructor-arg name="host" value="192.168.25.128"></constructor-arg> <constructor-arg 
        name="port" value="7005"></constructor-arg> </bean> <bean class="redis.clients.jedis.HostAndPort"> 
        <constructor-arg name="host" value="192.168.25.128"></constructor-arg> <constructor-arg 
        name="port" value="7006"></constructor-arg> </bean> </set> </constructor-arg> 
        <constructor-arg name="poolConfig" ref="jedisPoolConfig"></constructor-arg> 
        </bean> <bean id="jedisClientCluster" class="org.redis.impl..JedisClientCluster"></bean> -->
</beans>

 

java中redis分页查询

package common.model;

import java.util.ArrayList;
import java.util.List;

public class PageRedis<A>
{
	private int totalNum; // 总行数
	private int totalPage; // 总页数
	private int pageIndex; // 当前页数
	private int pageSize; // 每页几行

	private List<A> rows;

	public PageRedis()
	{

	}

	public int getTotalPage()
	{
		return totalPage;
	}

	public int getPageIndex()
	{
		return pageIndex;
	}

	public void setPageIndex(int pageIndex)
	{
		this.pageIndex = pageIndex;
	}

	public int getPageSize()
	{
		return pageSize;
	}

	public void setPageSize(int pageSize)
	{
		this.pageSize = pageSize;
	}

	public int getTotalNum()
	{
		return totalNum;
	}

	public void setTotalNum(int totalNum)
	{
		this.totalNum = totalNum;
	}

	// 设置总页数

	public List<A> getRows()
	{
		return rows;
	}

	public void setRows(List<A> rows)
	{
		this.rows = rows;
	}

	public void setTotalPage()
	{
		// 如果总行数整除每页的行数
		if (this.getTotalNum() % this.getPageSize() == 0)
		{
			this.totalPage = this.getTotalNum() / this.getPageSize();
		}
		else
		{
			this.totalPage = this.getTotalNum() / this.getPageSize() + 1;
		}
	}

	public <T> List<T> getPage(List<T> list)
	{
		List<T> sub = new ArrayList<T>();

		// 当前页的起始记录(非最后一页)
		int start = (this.getPageIndex() - 1) * this.getPageSize();

		// 当前页的截止记录(非最后一页)
		int end = this.getPageIndex() * this.getPageSize();

		// 最后一页
		int endOfLast = (this.getPageIndex() - 1) * this.getPageSize() + this.getTotalNum() % this.getPageSize();

		// 如果说,当前页数等于总页数 并且 总行数除以每页几行不能整除
		if (this.getPageIndex() == this.getTotalPage() && this.getTotalNum() % this.getPageSize() != 0)
		{
			for (int i = start; i < endOfLast; i++)
			{
				if (i < list.size())
				{
					sub.add(list.get(i));
				}
			}
		}
		else
		{
			for (int i = start; i < end; i++)
			{
				if (i < list.size())
				{
					sub.add(list.get(i));
				}
			}
		}

		return sub;
	}

	public static void main(String[] args)
	{
		/*List<Integer> list = new LinkedList<Integer>();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(5);

		PageRedis page = new PageRedis();
		page.setTotalNum(list.size());
		page.setPageSize(4);
		page.setPageIndex(3);
		page.setTotalPage();
		List<Integer> sub = page.getPage(list);
		System.out.println(sub);*/

	}
}

  

 

注意,上文中有几点是个人认为比较麻烦的

1.spring集成含密码的redis

2.利用redis的list和sortset实现分页查询

有问题欢迎讨论

 

以上是关于Java操作redis的主要内容,如果未能解决你的问题,请参考以下文章

jedis连接redis

Java操作Redis(代码演示)

Java代码redis基础操作

java操作redis都有哪些方法

redis用Java代码操作之Jedis用法

java操作redis都有哪些方法