Spring Boot 使用 Redis

作者: 就怕是个demo | 来源:发表于2016-12-29 09:25 被阅读610次

    1、首先引入依赖包

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-redis</artifactId>
    </dependency>
    <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.2.4</version>
    </dependency>
    

    2、为了能正确调用RedisTemplate,必须对其进行一些初始化工作,即主要对它存取的字符串进行一个JSON格式的系列化初始配置

    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.core.StringRedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    
    @Configurationpublic class RedisConfig {
        @Bean
        public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
            StringRedisTemplate template = new StringRedisTemplate(factory);
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(om);
            template.setValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
            return template;
        }
    }
    

    3、对于Redis,Spring Boot没有提供像JPA那样相应的资源库接口,所以只能仿照上一节中Repository的定义编写一个实体User的服务类。这个服务类可以存取对象User以及由User组成的列表List,同时还提供了一个删除的方法。所有这些方法都是使用RedisTemplate来实现的

    import java.util.List;
    import java.util.concurrent.TimeUnit;
    
    @Repositorypublic class UserRedis {    
        @Autowired
        private RedisTemplate<String, String> redisTemplate;
        /**
         * 保存数据到redis
         * @param key
         * @param time 过期时间
         * @param user
         */
        public void add(String key, long time, User user) {
            Gson gson = new Gson();
            redisTemplate.opsForValue().set(key, gson.toJson(user), time, TimeUnit.MINUTES);
        }
    
        public void add(String key, long time, List<User> users) {
            Gson gson = new Gson();
            redisTemplate.opsForValue().set(key, gson.toJson(users), time, TimeUnit.MINUTES);
        }
    
        public User get(String key) {
            Gson gson = new Gson();
            User user = null;
            String userJson = redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(userJson)) {
                user = gson.fromJson(userJson, User.class);
            }
            return user;
        }
    
        public List<User> getList(String key) {
            Gson gson = new Gson();
            List<User> ts = null;
            String listJson = redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(listJson)) {
                ts = gson.fromJson(listJson, new TypeToken<List<User>>(){}.getType());
            }
            return ts;
        }
    
        public void delete(String key) {
            redisTemplate.opsForValue().getOperations().delete(key);
        }
    }
    

    4、添加配置到application.yml

    spring:  
      datasource:
        url: jdbc:mysql://localhost:3306/xxxxx?characterEncoding=utf8&useSSL=true&verifyServerCertificate=false
        username: root
        password: xxxxx
        driver-class-name: com.mysql.jdbc.Driver
      jpa:
        database: MYSQL
        show-sql: true
        hibernate:
          ddl-auto: update
          naming:
            strategy: org.hibernate.cfg.ImprovedNamingStrategy
        properties:
          hibernate:
            dialect: org.hibernate.dialect.MySQL5Dialect
            enable_lazy_load_no_trans: true
      redis:
        host: 127.0.0.1
        port: 6379
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 0
          max-wait: -1
    #    database: 1
    

    5、测试

    import com.yp.domain.entity.Department;
    import com.yp.domain.entity.Role;
    import com.yp.domain.entity.User;import com.yp.domain.repository.UserRedis;
    import org.junit.Before;import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import java.util.Date;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class RedisTest {
        @Autowired
        UserRedis userRedis;
    
        @Before
        public void setUp() throws Exception {
            Department department = new Department();
            department.setName("开发部");
            Role role = new Role();
            role.setName("admin");
            User user = new User();
            user.setName("user");
            user.setDepartment(department);
            user.getRoles().add(role);
            user.setCreatedAt(new Date());
            userRedis.delete(this.getClass().getName()+":userByname:"+user.getName());
            userRedis.add(this.getClass().getName()+":userByname:"+user.getName(), 10L, user);    }
    
        @Test
        public void get() throws Exception {
            User user = userRedis.get(this.getClass().getName()+":userByname:user");
            System.err.println(user.getName());
            System.err.println(user.getDepartment().getName());
            System.err.println(user.getRoles().get(0).getName());
            System.err.println(user.getCreatedAt());
        }
    }
    

    6、结果


    相关文章

      网友评论

        本文标题:Spring Boot 使用 Redis

        本文链接:https://www.haomeiwen.com/subject/ybmuvttx.html