[置顶] SpringBoot系列—Redis使用

时间:2021-02-11 17:24:35

SpringBoot对redis的支持是通过Spring Data Redis 来时闲的,使用之前引入jar包:

compile('org.springframework.boot:spring-boot-starter-data-redis')

org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration为我们默认配置了JedisConnectionFactory、redisTemplate以及stringRedisTemplate,让我们直接可以使用redis作为数据存储。

org.springframework.boot.autoconfigure.data.redis.RedisProperties给我们展示了可以使用以“spring.redis”为前缀的属性在application.yml中配置redis。

例如,默认数据库为db0,在配置文件中将其设置为db1

spring:
redis:
database: 1

1.在docker下载redis镜像,并运行容器

2.新建对象User

package com.example.demo.bean;

import java.io.Serializable;

/**
* SpringBootDemo1
* Created by xian.juanjuan on 2017-6-19 14:15.
*/
public class User implements Serializable{

private static final long serialVersionUID = 934073895746700367L;
private String id;
private String name;
private Integer age;

public User(Integer age, String id, String name) {
super();
this.age = age;
this.id = id;
this.name = name;
}

get,set方法省略....
}
3.数据访问

package com.example.demo.dao;

import com.example.demo.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
* SpringBootDemo1
* Created by xian.juanjuan on 2017-6-19 14:17.
*/
@Repository
public class UserDao {

@Autowired
StringRedisTemplate stringRedisTemplate;

@Resource(name = "stringRedisTemplate")
ValueOperations<String, String> valOpsStr;

@Autowired
RedisTemplate<Object, Object > redisTemplate;

@Resource(name = "redisTemplate")
ValueOperations<Object, Object> valOps;

public void stringRedisTemplateDemo(){
valOpsStr.set("xx","yy");
}

public void save(User user){
valOps.set(user.getId(),user);
}

public String getString(){
return valOpsStr.get("xx");
}

public User getUser(String id){
return (User) valOps.get(id);
}

}
4.控制器,用userDao或RedisTemplate存取数据

package com.example.demo.controller;

import com.example.demo.bean.User;
import com.example.demo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* SpringBootDemo1
* Created by xian.juanjuan on 2017-6-19 14:26.
*/
@RestController
public class RedisDataController {

@Autowired
UserDao userDao;

@Autowired
RedisTemplate<Object,Object> redisTemplate;

@RequestMapping("/set")
public void set(){
User user = new User(32,"1","gg");
userDao.save(user);
userDao.stringRedisTemplateDemo();

redisTemplate.opsForValue().set("22",user);
}

@RequestMapping("/get1")
public String getString(){
return userDao.getString();
}

@RequestMapping("get2")
public User getUser(String id){
return userDao.getUser(id);
}
}

浏览器调用http://127.0.0.1:8082/set接口存数据

客户端查看

[置顶]        SpringBoot系列—Redis使用 [置顶]        SpringBoot系列—Redis使用

接口查看:

[置顶]        SpringBoot系列—Redis使用

客户端看到的数据是“乱码”,因为序列化引起,解决办法:自己配置redistemplate并定义Serializer

RedisTemplate使用的是JdkSerizationRedisSerializer,使用二级制形式存储数据,对于演示redis client不直观。

package com.example.demo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

/**
* SpringBootDemo1
* Created by xian.juanjuan on 2017-6-19 15:13.
*/
@Configuration
public class RedisConfig {

@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException{
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());

redisTemplate.afterPropertiesSet();

return redisTemplate;
}
}
设置value的序列化采用Jackson2JsonRedisSerializer,key的序列化采用StringRedisSerializer

重启项目,执行http://127.0.0.1:8082/set接口

客户端查看:

[置顶]        SpringBoot系列—Redis使用

接口查看:

[置顶]        SpringBoot系列—Redis使用


[置顶]        SpringBoot系列—Redis使用

序列化问题_no suitable constructor found

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.example.demo.bean.User: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
 at [Source: [B@3fbfca59; line: 1, column: 32]

User类使用时间序列化接口,使用Jackson序列化需要一个空构造,为什么?

public User() {
}
重启项目,接口访问正常~