SpringBoot系列—Redis使用

本文介绍了SpringBoot如何通过Spring Data Redis与Redis进行集成,详细讲解了自动配置的JedisConnectionFactory、redisTemplate及stringRedisTemplate的使用。在配置文件中,通过'spring.redis'前缀设置Redis数据库。在实际操作中,通过docker部署Redis,并遇到序列化问题,导致数据在客户端显示为乱码。为了解决这个问题,需要自定义redistemplate并指定Serializer,例如使用Jackson进行序列化。但在实现过程中,由于User类缺少默认构造函数,导致JsonMappingException。解决方法是让User类实现序列化接口或添加默认构造函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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接口存数据

客户端查看


接口查看:


客户端看到的数据是“乱码”,因为序列化引起,解决办法:自己配置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接口

客户端查看:

接口查看:




序列化问题_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() {
}
重启项目,接口访问正常~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值