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

3 篇文章 0 订阅
1 篇文章 0 订阅

从网上搜索到关于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

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值