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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章