zoukankan      html  css  js  c++  java
  • Spring Boot中使用Redis数据库

    引入依赖

      Spring Boot提供的数据访问框架Spring Data Redis基于Jedis。可以通过引入spring-boot-starter-redis来配置依赖关系。

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

    参数配置

      在application.properties中加入Redis服务端的相关配置,具体说明如下:

    # Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=localhost
    # Redis服务器连接端口
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.pool.max-active=8
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.pool.max-wait=-1
    # 连接池中的最大空闲连接
    spring.redis.pool.max-idle=8
    # 连接池中的最小空闲连接
    spring.redis.pool.min-idle=0
    # 连接超时时间(毫秒)
    spring.redis.timeout=0

      其中spring.redis.database的配置通常使用0即可,Redis在配置的时候可以设置数据库数量,默认为16,可以理解为数据库的schema

    测试访问

      通过编写测试用例,举例说明如何访问Redis。

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(Application.class)
    public class ApplicationTests {
    
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
    
        @Test
        public void test() throws Exception {
    
            // 保存字符串
            stringRedisTemplate.opsForValue().set("aaa", "111");
            Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
    
        }
    
    }

      上面的例子中,我们使用StringRedisTemplate对象进行Redis的读写操作,该对象从命名中就可注意到支持的是String类型。如果有使用过spring-data-redis的开发者一定熟悉RedisTemplate<K, V>接口,StringRedisTemplate就相当于RedisTemplate<String, String>的实现。

      除了String类型,实战中我们还经常会在Redis中存储对象,这时候我们就会想是否可以使用类似RedisTemplate<String, User>来初始化并进行操作。但是Spring Boot并不支持直接使用,需要我们自己实现RedisSerializer<T>接口来对传入对象进行序列化和反序列化,下面我们通过一个实例来完成对象的读写操作。

      创建要存储的对象:User

    public class User implements Serializable {
    
        private static final long serialVersionUID = -1L;
    
        private String username;
        private Integer age;
    
        public User(String username, Integer age) {
            this.username = username;
            this.age = age;
        }
    
        // 省略getter和setter
    
    }

      实现对象的序列化接口

    public class RedisObjectSerializer implements RedisSerializer<Object> {
    
      private Converter<Object, byte[]> serializer = new SerializingConverter();
      private Converter<byte[], Object> deserializer = new DeserializingConverter();
    
      static final byte[] EMPTY_ARRAY = new byte[0];
    
      public Object deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
          return null;
        }
    
        try {
          return deserializer.convert(bytes);
        } catch (Exception ex) {
          throw new SerializationException("Cannot deserialize", ex);
        }
      }
    
      public byte[] serialize(Object object) {
        if (object == null) {
          return EMPTY_ARRAY;
        }
    
        try {
          return serializer.convert(object);
        } catch (Exception ex) {
          return EMPTY_ARRAY;
        }
      }
    
      private boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
      }
    }

      配置针对User的RedisTemplate实例

    @Configuration
    public class RedisConfig {
    
        @Bean
        JedisConnectionFactory jedisConnectionFactory() {
            return new JedisConnectionFactory();
        }
    
        @Bean
        public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
            RedisTemplate<String, User> template = new RedisTemplate<String, User>();
            template.setConnectionFactory(jedisConnectionFactory());
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new RedisObjectSerializer());
            return template;
        }
    
    
    }

    测试案例:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(Application.class)
    public class ApplicationTests {
    
        @Autowired
        private RedisTemplate<String, User> redisTemplate;
    
        @Test
        public void test() throws Exception {
    
            // 保存对象
            User user = new User("u1", 20);
            redisTemplate.opsForValue().set(user.getUsername(), user);
    
            Assert.assertEquals(20, redisTemplate.opsForValue().get("u1").getAge().longValue());
    
        }
    
    }

    更加详细的spring data redis操作,请参考:https://docs.spring.io/spring-data/redis/docs/1.6.2.RELEASE/reference/html/

     

  • 相关阅读:
    zepto的源代码注释(转)
    关于js的连续赋值
    一道js题
    深入理解setTimeout的作用域
    深入理解setTimeout和setinterval
    webapp之路--apple私有属性apple-touch-icon
    javascript中的原型继承
    webapp之路--百度手机前端经验(转)
    (转)浏览器的渲染原理
    node.js study: cluster
  • 原文地址:https://www.cnblogs.com/senlinyang/p/8654167.html
Copyright © 2011-2022 走看看