##redis 应用场景1->获取最新的N条数据

#

如果项目中有获取最新的文章,或者最新的5000条评论时,可以考虑采用 redis中的List 来做,如果你还有别的需求,可以新建一个keylist,用来 保存你的最新N条记录.

##应用场景2->获取topN

这个是以score为权重去做top取值的,可以正序或者倒叙。 zadd topic 10 www.google.com 20 www.baidu.com, zrang topic 0 10 withscores 正序, zrevrange topic 0 10 withscores 倒叙.

##具体命令参考redis文档. http://redisdoc.com/

代码简化如下: 这里只贴出了代码片段. 2、参考 http://ask.chinaunix.net/question/33

##Test.java

package org.wendy.spring.redis.service;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Set;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.util.CollectionUtils;
import org.wendy.spring.redis.dao.RedisService;

@ContextConfiguration(locations = { "classpath*:applicationContext.xml" })
public class RedisServiceTest extends AbstractJUnit4SpringContextTests {

	@Autowired
	private RedisService redisService;

	@Test
	public void testSet() {
		String key = "name4";
		redisService.set(key, "wendy");
	}

	@Test
	public void testKeys() {

		Set<byte[]> keys = redisService.keys("*");

		if (!CollectionUtils.isEmpty(keys)) {
			for (byte[] bs : keys) {
				System.out.println(new String(bs));
			}
		}
	}

	@Test
	public void testGetString() {
		System.out.println(redisService.getString("name"));

		try {
			System.out
					.println(redisService.getString("name1".getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}
	
	@Test
	public void testSetEx(){
		redisService.setEx("name5", "zhangsan", 5);
		
	}

	@Test
	public void testGet() {
		
		

	}
	@Test
	public void testLpush(){
		redisService.lPush("languelist", "GO,JAVA");
		redisService.lPush("languelist".getBytes(), "swift,php,shell".getBytes());
	}
	
	@Test 
	public void testLtrim(){
		redisService.lTrim("languelist".getBytes(), 0, 9);
	}
	/*最新的N条记录.*/
	@Test
	public void testLeastN(){
		byte[] keyList = "languelist".getBytes();
		//在原有的基础上存入20条数据
		for (int i = 0; i < 20; i++) {
			redisService.lPush(keyList, ("id-"+i).getBytes());
		}
		//执行Ltrim 保持languelist里只有10条最新的记录.
		redisService.lTrim(keyList, 0, 9);
		
		//通过Lrange 获取最新的10条记录
		List<byte[]> list = redisService.lRange(keyList, 0, -1);
		if(list!=null&&!list.isEmpty()){
			for (byte[] bs : list) {
				System.out.println(new String(bs));
			}
		}
	}
	@Test
	public void testTopN(){
		byte[] zkey = "topic".getBytes();
		
		//通过各种手段把数据处理成 id  score 的样式,存入redis里.
		for (int i = 0; i < 20; i++) {
			redisService.zadd(zkey, Math.random(), ("wenzhang-id:"+i).getBytes());
		}
		//获取top 15.
		Set<byte[]> set = redisService.zrang(zkey, 0, 14);
		if(set!=null&&!set.isEmpty()){
			for (byte[] bs : set) {
				System.out.println(new String(bs));
			}
		}
		
		//获取倒叙的top 15
		Set<Tuple> setTop = redisService.zrevrangeWithScores(zkey, 0, 14);
		for (Tuple tuple : setTop) {
			System.out.println("socre="+tuple.getScore()+"value="+new String(tuple.getValue()));
			
		}
	}
	

}



##最新的N条记录,以时间为权重输出结果:

##topN 以score为权重,输出结果如下:

##RedisService.java

	package org.wendy.spring.redis.dao;

import java.util.List;
import java.util.Set;

import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;


public interface RedisService {

	public void set(final String key, final String value);

	public void setEx(final String key, final String value,
			final long expireSeconds);

	public Set<byte[]> keys(String pattern);

	public String getString(String key);

	public String getString(byte[] key);

	public byte[] get(String key);

	public byte[] get(byte[] key);

	/* List operate. */
	/* LPUSH 操作 获取最新的N条记录.每次只能操作一个元素 */
	public Long lPush(String keyList, String values);

	public Long lPush(byte[] keyList, byte[] values);

	/* start from 0 begin. */
	public void lTrim(byte[] keyList, long start, long end);

	public List<byte[]> lRange(byte[] keyList, long begin, long end);

	/* 添加有续集.SortedSet */

	public boolean zadd(byte[] zkey, double score, byte[] value);

	/* get value from sortedset. */
	public Set<byte[]> zrang(byte[] zkey, long begin, long end);
	
	public Set<Tuple> zrevrangeWithScores(byte[] zkey ,long begin ,long end);
	
	

}


##RedisServiceImpl.java

package org.wendy.spring.redis.dao;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;


/**
 * <b>time:</b>2015年3月11日
 *
 * @author admin
 *
 */
@Component
public class RedisServiceImpl implements RedisService {
	@Autowired
	private RedisTemplate<Serializable, Serializable> redisTemplate;

	private RedisSerializer<String> getStringRedisSerializable() {
		return redisTemplate.getStringSerializer();
	}

	public void set(final String key, final String value) {

		String values = redisTemplate.execute(new RedisCallback<String>() {

			public String doInRedis(RedisConnection connection)
					throws DataAccessException {
				connection.set(
						redisTemplate.getStringSerializer().serialize(key),
						redisTemplate.getStringSerializer().serialize(value));
				return value;
			}
		});
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>" + values);
	}

	public Set<byte[]> keys(final String pattern) {
		return redisTemplate.execute(new RedisCallback<Set<byte[]>>() {
			public Set<byte[]> doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.keys(redisTemplate.getStringSerializer()
						.serialize(pattern));
			}
		});

	}

	public String getString(final String key) {

		return redisTemplate.execute(new RedisCallback<String>() {

			public String doInRedis(RedisConnection connection)
					throws DataAccessException {
				byte[] value = connection.get(getStringRedisSerializable()
						.serialize(key));
				if (value != null) {
					return new String(value);
				}
				return null;
			}
		});

	}

	public String getString(final byte[] key) {
		return redisTemplate.execute(new RedisCallback<String>() {

			public String doInRedis(RedisConnection connection)
					throws DataAccessException {
				byte[] value = connection.get(key);
				if (value != null) {
					return new String(value);
				}
				return null;
			}
		});
	}

	public byte[] get(final String key) {
		return redisTemplate.execute(new RedisCallback<byte[]>() {

			public byte[] doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.get(getStringRedisSerializable().serialize(
						key));

			}
		});
	}

	public byte[] get(final byte[] key) {
		return redisTemplate.execute(new RedisCallback<byte[]>() {
			public byte[] doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.get(key);
			}
		});
	}

	public void setEx(final String key, final String value,
			final long expireSeconds) {

		redisTemplate.execute(new RedisCallback<Object>() {

			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {

				connection.setEx(getStringRedisSerializable().serialize(key),
						expireSeconds,
						getStringRedisSerializable().serialize(value));
				return null;
			}
		});

	}

	public Long lPush(final String keyList, final String values) {

		return redisTemplate.execute(new RedisCallback<Long>() {

			public Long doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.lPush(
						getStringRedisSerializable().serialize(keyList),
						getStringRedisSerializable().serialize(values));
			}
		});

	}

	public Long lPush(final byte[] keyList, final byte[] values) {
		return redisTemplate.execute(new RedisCallback<Long>() {
			public Long doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.lPush(keyList, values);
			}
		});
	}

	public void lTrim(final byte[] keyList, final long start, final long end) {
		redisTemplate.execute(new RedisCallback<Boolean>() {
			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				connection.lTrim(keyList, start, end);
				return true;
			}
		});

	}

	public List<byte[]> lRange(final byte[] keyList, final long begin,
			final long end) {

		return redisTemplate.execute(new RedisCallback<List<byte[]>>() {

			public List<byte[]> doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.lRange(keyList, begin, end);
			}
		});

	}

	public boolean zadd(final byte[] zkey, final double score,
			final byte[] value) {

		return redisTemplate.execute(new RedisCallback<Boolean>() {

			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.zAdd(zkey, score, value);
			}

		});

	}

	public Set<byte[]> zrang(final byte[] zkey, final long begin, final long end) {

		return redisTemplate.execute(new RedisCallback<Set<byte[]>>() {

			public Set<byte[]> doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.zRange(zkey, begin, end);
			}
		});

	}

	public Set<Tuple> zrevrangeWithScores(final byte[] zkey, final long begin,
			final long end) {

		return redisTemplate.execute(new RedisCallback<Set<Tuple>>() {

			public Set<Tuple> doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.zRevRangeWithScores(zkey, begin, end);
			}

		});

	}

}