5fd3421f163fc4207.jpg_fo742.jpg

pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

application.yml

server:
  port: 8888

spring:
  application:
    name: redis
  redis:
    host: 127.0.0.1
    timeout: 1000ms
    jedis:
      pool:
        max-active: 0
        max-idle: -1
        max-wait: -1ms
        min-idle: 0

RedisController.java

@RestController
public class RedisController {

    @Resource
    private StringRedisTemplate stringRedisTemplate ;

    @RequestMapping("/setGet")
    public String setGet (){
        stringRedisTemplate.opsForValue().set("foo","bar");
        return stringRedisTemplate.opsForValue().get("foo") ;
    }

    @Resource
    private RedisTemplate redisTemplate ;

    /**
     * 设置 Key 的有效期 10 秒
     */
    @RequestMapping("/setKeyTime")
    public String setKeyTime (){
        redisTemplate.opsForValue().set("timeKey","timeValue",10, TimeUnit.SECONDS);
        return "success" ;
    }
    @RequestMapping("/getTimeKey")
    public String getTimeKey (){
        // 这里 Key 过期后,返回的是字符串 'null'
        return String.valueOf(redisTemplate.opsForValue().get("timeKey")) ;
    }
}

RedisConfig.java 序列化

@Configuration
public class RedisConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class) ;
    /**
     * 序列化配置
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate
            (LettuceConnectionFactory  redisConnectionFactory) {
        LOGGER.info("RedisConfig == >> redisTemplate ");
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

SerializeController.java 序列化

@RestController
public class SerializeController {

    @Resource
    private RedisTemplate redisTemplate ;

    @RequestMapping("/setUser")
    public String setUser (){
        User user = new User() ;
        user.setName("test");
        user.setAge(22);
        List<String> list = new ArrayList<>() ;
        list.add("1");
        list.add("a");
        list.add("))))");
        list.add("中文");
        user.setEducation(list);
        redisTemplate.opsForValue().set("userInfo",user);
        return "success" ;
    }

    @RequestMapping("/getUser")
    public User getUser (){
        return (User)redisTemplate.opsForValue().get("userInfo") ;
    }
}

客户端


序列化:

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code