码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot快速整合redis

时间:2021-06-18 19:19:32      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:base   port   art   autowired   ret   autowire   start   org   public   

添加依赖

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

添加yml配置

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:
    timeout: 1000
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    luttuce:
      shutdown-timeout: 0

使用

 @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void setRedisValue() {
        char[] a = new char[2*1024];
        String s = JSON.toJSONString(a);
        redisTemplate.opsForValue().set("user", s);
    }

序列化

默认的redis序列化为StringRedisSerializer,value只能设置string字符串,如果想保存对象,需要设置序列化方法。

@Configuration
public class RedisConfiguration {


    @Bean()
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
    {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(stringRedisSerializer);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

使用

 @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void setRedisValue() {
        User user = new User();
        user.name = "spring";
        user.age = 18;
        redisTemplate.opsForValue().set("user", user);
    }

    private class User
    {
        private String name;

        private int age;
    }

spring boot快速整合redis

标签:base   port   art   autowired   ret   autowire   start   org   public   

原文地址:https://www.cnblogs.com/springs018/p/14897691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!