添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.apache.commons</groupId>
  7. <artifactId>commons-pool2</artifactId>
  8. </dependency>

添加redis服务器信息

application.yml

  1. spring:
  2. redis:
  3. host: eurekaserver01.com
  4. password: EanD5NhsdCWLs6zs
  5. port: 6379
  6. # 连接超时时间(记得添加单位,Duration)
  7. timeout: 10000ms
  8. # Redis默认情况下有16个分片,这里配置具体使用的分片
  9. # database: 0
  10. lettuce:
  11. pool:
  12. # 连接池最大连接数(使用负值表示没有限制) 默认 8
  13. max-active: 8
  14. # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
  15. max-wait: -1ms
  16. # 连接池中的最大空闲连接 默认 8
  17. max-idle: 8
  18. # 连接池中的最小空闲连接 默认 0
  19. min-idle: 0
  20. cache:
  21. # 一般来说是不用配置的,Spring Cache 会根据依赖的包自行装配
  22. type: redis

注册redis config bean

  1. @Configuration
  2. @AutoConfigureAfter(RedisAutoConfiguration.class)
  3. @JsonIgnoreProperties(ignoreUnknown = true)
  4. public class RedisConfig {
  5. @Bean
  6. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
  7. RedisTemplate<String, Object> template = new RedisTemplate<>();
  8. template.setConnectionFactory(redisConnectionFactory);
  9. template.setKeySerializer(new StringRedisSerializer());
  10. template.setValueSerializer(new RedisObjectSerializer());
  11. return template;
  12. }
  13. }

Object序列化:

  1. public class RedisObjectSerializer implements RedisSerializer<Object> {
  2. private final Converter<Object, byte[]> serializer = new SerializingConverter();
  3. private final Converter<byte[], Object> deSerializer = new DeserializingConverter();
  4. private static final byte[] EMPTY_ARRAY = new byte[0];
  5. @Override
  6. public byte[] serialize(Object o) throws SerializationException {
  7. if (o == null) {
  8. return EMPTY_ARRAY;
  9. }
  10. return serializer.convert(o);
  11. }
  12. @Override
  13. public Object deserialize(byte[] bytes) throws SerializationException {
  14. if (isEmpty(bytes)) {
  15. return null;
  16. }
  17. return deSerializer.convert(bytes);
  18. }
  19. private boolean isEmpty(byte[] data) {
  20. return data == null || data.length == 0;
  21. }
  22. }

使用方式

  1. public User getUserById(Long id) {
  2. Object obj = redisObjTemplate.opsForValue().get(String.valueOf(id));
  3. User user;
  4. if (obj != null) {
  5. log.info("data from redis");
  6. user = (User) obj;
  7. } else {
  8. user = userMapper.selectById(id);
  9. if (user != null) {
  10. redisObjTemplate.opsForValue().set(String.valueOf(id), user);
  11. }
  12. }
  13. return user;
  14. }