10、SpringBoot中使用Redis

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


      org.springframework.boot
      spring-boot-starter-data-redis
      2.1.6.RELEASE

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

你可能感兴趣的:(10、SpringBoot中使用Redis)