Redis Springboot整合

2021-03-2298

在pom中添加特定依赖spring-boot-starter-data-redis

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

重新定义RedisTemplate

@Configuration
public class RedisConfig {

   @Bean
   @SuppressWarnings("all")
   public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
       System.out.println("**************Reached************");
       RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
       template.setConnectionFactory(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);
       StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

       // key采用String的序列化方式
       template.setKeySerializer(stringRedisSerializer);
       // hashkey也采用String的序列化方式
       template.setHashKeySerializer(stringRedisSerializer);
       // value序列化方式采用jackson
       template.setValueSerializer(jackson2JsonRedisSerializer);
       // hashvalue序列化方式采用jackson
       template.setHashValueSerializer(jackson2JsonRedisSerializer);
       template.afterPropertiesSet();

       return template;
   }
}

编写RedisUtil类

--见 附件

编写测试类

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test_1{

   @Autowired
   RedisUtil redisUtil;


   @Test
   public void set(){
       redisUtil.set("myKey","666");
       System.out.println(redisUtil.get("myKey"));
   }

测试结果666

上一篇:RedisUtil类 下一篇:Redis 哨兵模式