SpringBoot整合Redis

1、导入依赖(Redis整合在SpringData中)
<!--springboot2.x之后,不在使用Jedis,而是替换成了lettuce
	Jedis:采用的是直连的方式,多个线程操作的话,存在线程安全问题,可以采用jedis pool连接池来避免线程安全问题
	lettuc:采用netty,实例可以在多个线程中共享,不存在线程安全问题-->
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置连接
server:
  port: 8001

spring:
  application:
    name: redis
  redis:
    host: 112.124.15.80
    port: 6379
3、测试
@Autowired
    private RedisTemplate redisTemplate;
    @Test
    void contextLoads() {
        //opsForValue操作字符串
        //opsForList操作list
        //opsForSet操作set
        //opsForHash操作hash

        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();

        redisTemplate.opsForValue().set("name","zhangsan");
        System.out.println(redisTemplate.opsForValue().get("name"));
    }
4、对象存储
 @Test
    public void test() throws JsonProcessingException {
        User user = new User("zhangsan",15);
        //将对象转换成json格式字符串
        //如果直接将对象保存到redis中,对象实体类需要序列化
        String jsonString = new ObjectMapper().writeValueAsString(user);
        redisTemplate.opsForValue().set("user",jsonString);
        System.out.println(redisTemplate.opsForValue().get("user"));
    }
5、自定义redis配置
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        //为了开发方便,一般直接使用<String,Object>
        RedisTemplate<String,Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);

        //json序列化设置
        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);
        //String序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //key采用String序列化的方式
        template.setKeySerializer(stringRedisSerializer);
        //hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //value的序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页