redis怎么存取java实体
时间: 2023-11-30 09:39:55 浏览: 138
spring mvc + lombok + redis
在Java中,我们可以使用RedisTemplate来存取Java实体。首先,我们需要配置RedisTemplate,可以通过实现Redis的序列化来实现。可以使用FastJsonRedisSerializer类来实现序列化。接着,我们可以使用redisTemplate.opsForValue().set()方法来将Java实体存入Redis中,其中需要将Java实体转换为JSON字符串。在获取Java实体时,我们可以使用redisTemplate.opsForValue().get()方法获取JSON字符串,然后使用JSON.parseObject()方法将JSON字符串转换为Java实体。具体实现可以参考以下代码:
1. 配置类:
```
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer<>(Object.class));
return redisTemplate;
}
}
class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
}
```
2. 实体类:
```
public class UserVO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String password;
// getter and setter
}
```
3. 存入Java实体:
```
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void setUser(UserVO user) {
redisTemplate.opsForValue().set("user:" + user.getId(), user);
}
```
4. 获取Java实体:
```
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public UserVO getUser(Long id) {
return (UserVO) redisTemplate.opsForValue().get("user:" + id);
}
```
阅读全文