Spring Boot 使用 Redis

1、首先引入依赖包


   org.springframework.boot
   spring-boot-starter-redis


   com.google.code.gson
   gson
   2.2.4

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 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 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 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 getList(String key) {
        Gson gson = new Gson();
        List ts = null;
        String listJson = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(listJson)) {
            ts = gson.fromJson(listJson, new TypeToken>(){}.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_第1张图片

你可能感兴趣的