使用StringRedisTemplate和外部反序列化操作redis

从网上搜索到关于RedisTemplate<String, Object>自动序列化的方式操作redis,经使用发现如果实体类有整形属性,反序列化时会出错,采用了外部序列化和反序列化的方式结合StringRedisTemplate实现了存取实体类。过程如下:

引入依赖

<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.47</version>
</dependency> 

建实体类

package com.wsk.test.model;

public class Person {
	private String name;
	private int age;
		
	public Person(String name, int age) {		
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}	
}

服务类

package com.wsk.test.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.wsk.test.model.Person;

@Service
public class RedisService {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	public void set(String key, Person data) {
		String objectToJson = JSON.toJSONString(data); 
		stringRedisTemplate.opsForValue().set(key, objectToJson);
	}

	public Person get(String key) {
		String res=stringRedisTemplate.boundValueOps(key).get();
		if(res==null) return null;
		Person data = JSON.parseObject(res, Person.class);
		return data;
	}
	
	public Boolean delete(String key) {
		return stringRedisTemplate.delete(key);
	}
}

测试

package com.wsk.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.wsk.test.model.Person;
import com.wsk.test.utils.RedisService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {
		
	@Autowired
	private RedisService redisService; 
	
	@Test
	public void RedisTestCase() {
		redisService.set("key",new Person("zhangsan", 18));
		Person person=redisService.get("key");
		
		System.out.println(person.getName()+":"+person.getAge());
	}
}

输出

zhangsan:18
发布了7 篇原创文章 · 获赞 1 · 访问量 1520

猜你喜欢

转载自blog.csdn.net/mmmbox/article/details/89444475
今日推荐