Solve the problem of memcached being stored in list<bean>

Dolphin Elf : https://mgo.whhtjl.com

Today, when I used memcached to access List<bean>, I encountered a problem. It was normal to save String, but failed when saving bean. I found various information on the Internet. Some people said that memcached cannot save List<bean>. Some people say to use HashMap. The last solution I found is to use fastjson to serialize List<bean>, store it in memcached, and then deserialize it when it is taken out. It succeeded. The specific implementation:

1. Download the jar package of fastjson, I use the latest fastjson-1.1.28.jar

2. Serialize the stored code

package com.ltf.cache;

import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.ltf.entity.Course;

/**
 * 缓存工具类
 * @author xhz
 *
 */
public class CacheUtil {

	private static MemCache memCache = MemCache.getInstance();

	public CacheUtil() {
	}

	public static boolean isArrayList(Object obj) {
		if(obj==null) {
			return false;
		}else if(obj.getClass().getSimpleName().equals("ArrayList")) {
			return true;
		}
		return false;
	}

	/**
	 * 存值
	 * @param key
	 * @param value
	 */
	public static void set(String key, Object value) {
		try {
			if(isArrayList(value)) {
				memCache.set(key,JSON.toJSONString(value));
			}else {
				memCache.set(key,value);
			}
		} catch (Exception var3) {
			var3.printStackTrace();
		}
	}
	
	/**
	 * 根据key取值 仅供ArrayList使用
	 * @param key
	 * @return
	 */
	public static <T> List<T> get(String key,Class<T> clazz) {
		try {
			if(memCache.get(key)==null)
				return null;
			return JSON.parseArray(memCache.get(key).toString(),clazz);
		} catch (Exception var2) {
			var2.printStackTrace();
		}
		return null;
	}

}

3. Deserialize and take out

     public static void main(String[] args) {
		List<Course> test=new ArrayList<Course>();
		Course log1 = new Course();
		log1.setCourseName("test");
		log1.setDescribe("测试描述");
		test.add(log1);
		Course log2 = new Course();
		log2.setCourseName("test2");
		log2.setDescribe("测试描述2");
		test.add(log2);
		CacheUtil.set("tetttt", test);
		List<Course> list=CacheUtil.get("tetttt",Course.class);
		for (Course course : list) {
			System.out.println(course);
		}
    }

OK, you're done!

Guess you like

Origin blog.csdn.net/qq_35393693/article/details/107738195