Redis(1)-redisで商品を格納する-ユーザ関係

11515 ワード

package com.lipeng;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;

public class UserSerivce {

	private RedisTemplate redisTemplate;
	HashOperations ho;

	public UserSerivce() {
		/**
		 *       
		 */
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-redis.xml");
		redisTemplate = (RedisTemplate) ac.getBean("redisTemplate");
	}

	/**
	 *         
	 * 
	 * @param uId
	 * @param pId
	 */
	public void addLove(String uId, String pId) {
		//            
		final String uKey = getUKey(uId);
		final String uHashKey = pId + "";
		final String pKey = getPKey(pId);
		final String pHashKey = uId + "";
		final Date date = new Date();
		SessionCallback call = new SessionCallback() {

			public Object execute(RedisOperations ops) throws DataAccessException {
				// TODO Auto-generated method stub
				ops.multi();
				ho = ops.opsForHash();
				ho.put(uKey, uHashKey, date);
				ho.put(pKey, pHashKey, date);
				ops.exec();
				return null;
			}
		};
		redisTemplate.execute(call);
		//      +1

	}

	/**
	 *     
	 * 
	 * @param uId
	 * @param pId
	 */
	public void cannelLove(String uId, String pId) {
		final String uKey = getUKey(uId);
		final String pIdStr = pId;
		final String pKey = getPKey(pId);
		final String uIdStr = uId;
		SessionCallback call = new SessionCallback() {

			public Object execute(RedisOperations ops) throws DataAccessException {
				// TODO Auto-generated method stub
				ops.multi();
				ho = ops.opsForHash();
				ho.delete(uKey, pIdStr);
				ho.delete(pKey, uIdStr);
				ops.exec();
				return null;
			}
		};
		redisTemplate.execute(call);
	}

	/**
	 *           
	 * 
	 * @param uId
	 * @param pId
	 */
	public boolean isLoved(String uId, String pId) {
		boolean re = false;
		final String uKey = getUKey(uId);
		final String uHashKey = pId + "";
		ho = redisTemplate.opsForHash();
		System.out.println(uKey + "  ,   " + uHashKey);
		re = ho.hasKey(uKey, uHashKey);
		return re;
	}

	/**
	 *          
	 * 
	 * @return
	 */
	public Long getLoveCountByUid(String uId) {
		final String uKey = getUKey(uId);
		long re = 0;
		ho = redisTemplate.opsForHash();
		re = ho.size(uKey);
		return re;
	}

	/**
	 *       
	 * 
	 * @return
	 */
	public Long getLoveCountByPid(String pId) {
		final String pKey = getPKey(pId);
		long re = 0;
		ho = redisTemplate.opsForHash();
		re = ho.size(pKey);
		return re;
	}

	/**
	 *     
	 */

	public void delP(String pId) {
		//          

		//              

		final String pKey = getPKey(pId);
		final String pIdStr = pId + "";
		final Set keys = redisTemplate.keys("uId:*:p");
		SessionCallback call = new SessionCallback() {

			public Object execute(RedisOperations ops) throws DataAccessException {
				// TODO Auto-generated method stub
				ho = ops.opsForHash();
				ops.delete(pKey);
				if (keys != null && keys.size() > 0) {
					for (String key : keys) {
						if (ho.hasKey(key, pIdStr)) {//           ,         ,        multi ,
							//  multi               ,   exec     ,ho.hashKey()   null;
							System.out.println(pIdStr);
							ho.delete(key, pIdStr);
						}
					}
				}
				return null;
			}
		};

		redisTemplate.execute(call);
	}

	/**
	 *          
	 * 
	 * @param pId
	 * @param count
	 * @return
	 */
	public Map getUidsByPid(String pId, int count) {
		Map map = null;
		final String pKey = getPKey(pId);
		SessionCallback> call = new SessionCallback>() {

			public Map execute(RedisOperations ops) throws DataAccessException {
				// TODO Auto-generated method stub
				ops.multi();
				ho = ops.opsForHash();
				ops.exec();
				return (Map) ho.entries(pKey);
			}
		};
		map = redisTemplate.execute(call);
		return map;
	}

	/**
	 *          
	 * 
	 * @param uId
	 * @return
	 */
	private Map getPidsByUid(String uId) {
		Map map = null;
		final String uKey = getUKey(uId);
		SessionCallback> call = new SessionCallback>() {

			public Map execute(RedisOperations ops) throws DataAccessException {
				// TODO Auto-generated method stub
				ops.multi();
				ho = ops.opsForHash();
				ops.exec();
				return (Map) ho.entries(uKey);
			}
		};
		map = redisTemplate.execute(call);
		return map;
	}

	/**
	 *          ids
	 * 
	 * @param uId
	 * @return
	 */
	public List getFocusPids(String uId) {
		return sortIds(this.getPidsByUid(uId));
	}

	/**
	 *        IDS
	 * 
	 * @param pId
	 * @return
	 */
	public List getFansUids(String pId) {
		return sortIds(this.getUidsByPid(pId, 0));
	}

	public static String getUKey(String uId) {
		return "uId:" + uId + ":p";
	}

	public static String getUCountKey(String uId) {
		return "uId:" + uId + ":pCount";
	}

	public static String getPKey(String pId) {
		return "pId:" + pId + ":u";
	}

	public static String getPCountKey(String pId) {
		return "pId:" + pId + ":uCount";
	}

	/**
	 *        
	 * 
	 * @param map
	 * @return
	 */
	public List sortIds(Map map) {
		List> list = new LinkedList>();
		list.addAll(map.entrySet());
		Collections.sort(list, new Comparator>() {
			public int compare(Map.Entry date1, Map.Entry date2) {//       

				if (date1.getValue().getTime() < date2.getValue().getTime())
					return 1;
				if (date1.getValue().getTime() == date2.getValue().getTime())
					return 0;
				else
					return -1;
			}
		});
		List ids = new ArrayList();
		for (Iterator> ite = list.iterator(); ite.hasNext();) {
			Map.Entry map1 = ite.next();
			System.out.println("key-value: " + map1.getKey() + "," + map1.getValue());
			ids.add(map1.getKey());
		}
		return ids;
	}

	/**
	 *          
	 * 
	 * @param pids
	 * @return key=pid value=fansCount
	 */
	public Map getFansCountByPids(List pids) {
		Map map = new HashMap();

		ho = redisTemplate.opsForHash();
		for (String pId : pids) {
			String pidKey = this.getPKey(pId);
			Long size = ho.size(pidKey);
			map.put(pId, size);
		}
		return map;
	}
	/**
	 *         count   id
	 * @param count
	 * @return
	 */
	public Map getHot(int count)
	{
		Mapmap=new HashMap();
		ho=redisTemplate.opsForHash();
		Set keys=redisTemplate.keys("pId:*:u");
		if(keys!=null)
		{
			for(String key:keys)
			{
				map.put(key, ho.size(key));
			}
		}
		return sortByCount(map,count);
	}
	
	public Map  sortByCount(Map map,int count)
	{
		Map re=new LinkedHashMap();
		List> list = new ArrayList>();
		list.addAll(map.entrySet());
		Collections.sort(list, new Comparator>() {
			public int compare(Map.Entry date1, Map.Entry date2) {//       

				if (date1.getValue()< date2.getValue())
					return 1;
				if (date1.getValue() == date2.getValue())
					return 0;
				else
					return -1;
			}
		});
		for (Iterator> ite = list.iterator(); ite.hasNext();) {
			Map.Entry map1 = ite.next();
			System.out.println("key-value: " + map1.getKey() + "," + map1.getValue());
			re.put(map1.getKey() , map1.getValue());
			if(re.size()==count)
			{
				return re;
			}
		}
		return re;
	}
	public static void main(String[] args) {
		UserSerivce us = new UserSerivce();

		 testAdds(us);

		// System.out.println(us.getLoveCountByPid(1));
		// System.out.println(us.getLoveCountByUid(3));
		// testCannelFocus(us);
		// testDel(us, uId, pId, list1, list2);
		// testGetFansCountByPids(us);
		//us.testMulti();
		Map map=us.getHot(2);
		System.out.println(map);
	}

	/**
	 *       
	 * 
	 * @param us
	 */
	private static void testCannelFocus(UserSerivce us) {
		String uId = "0";
		String pId = "0";
		List list1 = us.getFocusPids(uId);
		System.out.println("  " + uId + "     " + list1);
		System.out.println("  " + uId + "     " + pId + "   ");
		us.cannelLove(uId, pId);
		List list2 = us.getFocusPids(uId);
		System.out.println("  " + uId + "     " + list2);
		System.out.println(us.getLoveCountByPid("0"));
	}

	/**
	 *       
	 * 
	 * @param us
	 * @param uId
	 * @param pId
	 * @param list1
	 * @param list2
	 */
	private static void testDel(UserSerivce us, String uId, String pId, List list1, List list2) {
		System.out.println("  " + pId + "     " + list1);
		System.out.println("  " + uId + "     " + list2);
		System.out.println("      " + pId);
		us.delP(pId);
		System.out.println("    ");
		List list3 = us.getFansUids(pId);
		List list4 = us.getFocusPids(uId);
		System.out.println("  " + pId + "     " + list3);
		System.out.println("  " + uId + "     " + list4);
	}

	/**
	 *       
	 * 
	 * @param us
	 */
	private static void testAdds(UserSerivce us) {
		us.addLove("1", "1");
		us.addLove("2", "1");
		us.addLove("7", "3");
		us.addLove("8", "4");
		us.addLove("9", "4");
		us.addLove("1", "2");
		us.addLove("5", "3");
		us.addLove("4", "1");
	}

	/**
	 *             
	 * 
	 * @param us
	 */
	public static void testGetFansCountByPids(UserSerivce us) {
		List pids = new ArrayList();
		pids.add("1");
		pids.add("2");
		pids.add("3");
		pids.add("4");
		Map map = us.getFansCountByPids(pids);
		System.out.println(map);
	}

	public void testMulti() {
		redisTemplate.watch("a");
		redisTemplate.multi();
		redisTemplate.exec();
		redisTemplate.unwatch();
	}
}