10、SpringBoot中使用Redis

1、在pom.xml文件中引入Redis

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

aaplcation.yml文件配置Redis

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/springboot_cache?serverTimezone=UTC
    username: root
    password: 123456
  redis:
    host: 127.0.0.1
    port: 6379

2、Redis简单的测试


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootAdvanceCacheApplicationTests {

    @Autowired
    EmployeeMapper employeeMapper;


    @Autowired
    StringRedisTemplate stringRedisTemplate;  //操作 K-V都是字符串


    @Autowired
    RedisTemplate redisTemplate;  //K-V都是对象

    @Test
    public void test(){
        stringRedisTemplate.opsForValue().append("msg","hello");
    }


    @Test
    public void test01(){
        String msg = stringRedisTemplate.opsForValue().get("msg");
        System.out.printf("=="+msg);
    }
} 
e6mS0S.png
e6mPYj.png

3、将Redis应用到我们业务中

新建一个RddisConfig类

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
}

Service层代码

   @Cacheable(cacheNames = {"emp"})
   public Employee getEmpById(Integer id){
       System.out.println("查询"+id+"号员工");
       Employee employee = employeeMapper.getEmpById(id);
       return employee;
   }

记得在实体类上实现序列化!!!

public class Employee implements Serializable

不然会报

org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException:DefaultSerializer requires a Serializable payload but received an object of type[com.bx.cloud.common.auth.component.AuthSession]

然后运行程序

e6nyG9.png

我们发现存入Redis中是我们一些看不懂的,那么我们来将结果以json的方式存到Redis中

参考这篇文章:https://blog.csdn.net/caojidasabi/article/details/83059642

在我们上面编写的RedisConfig类中添加我们自定义的cacheManager方法


    @Configuration
    public class MyRedisConfig {
        @Bean
        public RedisTemplate<Object, Employee> empRedisTemplate(
                RedisConnectionFactory redisConnectionFactory)
                throws UnknownHostException {
            RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
            template.setConnectionFactory(redisConnectionFactory);
            Jackson2JsonRedisSerializer<Employee> jsonRedisSerializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
            template.setDefaultSerializer(jsonRedisSerializer);
            return template;
        }
    }
    //自定义cacheManager缓存管理器
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory)
    {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);

        //配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ZERO)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }

然后就会发现Redis中存储的是json形式的啦~


e6KS0K.png

推荐阅读更多精彩内容

  • RedisRedis命令参考网址:http://doc.redisfans.com/ Redis 简介Redis ...
    野柳阅读 734评论 0 9
  • 缓存是最直接有效提升系统性能的手段之一。个人认为用好用对缓存是优秀程序员的必备基本素质。 本文结合实际开发经验,从...
    Java小生阅读 324评论 1 2
  • 介绍 使用mybatis时可以使用二级缓存提高查询速度,进而改善用户体验。 使用redis做mybatis的二级缓...
    闫子扬阅读 384评论 1 0
  • 现在想想,大抵我的童年应该还是幸福的,逛某宝偶尔看到这样那样的物什总能勾起我的回忆,都是记忆里关于美好的回忆…...
    120分贝阅读 718评论 0 0
  • 第一天,小白兔去钓鱼,一无所获。第二天,它又去钓鱼,还是如此。第三天它刚到,一条大鱼从河里跳出来,大叫:你要是再敢...
    语馨_f389阅读 73评论 0 0