栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Redis 学习笔记(四)-- SpringBoot集成Redis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Redis 学习笔记(四)-- SpringBoot集成Redis

SpringBoot 操作数据: Spring Data 也是与之齐名的项目。

说明:在 springboot 2.X 之后,原来使用的 Jedis 被替换成了 lettuce

  • Jedis: 采用直连,多个线程操作的话是不安全的;如果要避免不安全的,使用 Jedis pool 连接池!更像 BIO 模式。

  • lettuce: 采用 netty,实例可以在多个线程中共享!不存在不安全的情况,可以减少线程数据!更像 NIO 模式。

源码:

public class RedisAutoConfiguration {
	// 默认的 redisTemplate 没有过多的设置, redis对象保存都是需要序列化的
    // 两个泛型都是  的类型,使用的需要强制类型转换 
	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	@ConditionalOnSingleCandidate(RedisConnectionFactory.class)	// 我们可以自定义一个 redisTemplate Bean 来替换默认的!
	public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

	@Bean
	@ConditionalOnMissingBean	// 由于 String 时 Redis 中最常用的类型,所以单独提出来的一个Bean 操作String类型直接使用
	@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		return new StringRedisTemplate(redisConnectionFactory);
	}

}

整合测试

1、导入依赖


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

2、配置文件

# 配置 Redis
spring.redis.host=192.168.40.25
spring.redis.port=6379

# 源码中 Jedis 根本没生效,不能使用 Jedis 的配置
# spring.redis.jedis.pool.enabled=true
# 使用 lettuce 的配置
# spring.redis.lettuce.pool.enabled=true

3、使用测试

@SpringBootTest
class Redis02SpringbootApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        // opsForValue 操作字符串 类似 String
        // opsForList 操作list 类似 List
        // opsForSet
        // opsForZSet
        // opsForHash
        // 获取连接
//        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//        connection.flushDb();
//        connection.flushAll();

        redisTemplate.opsForValue().set("key", "Hello redis!");
        System.out.println(redisTemplate.opsForValue().get("key"));
    }
}

源码中的序列化配置:

默认的序列化是使用 JDK 序列化,我们可能使用 JSON 来序列化!

自定义 redisTemplate

测试

    @Test
    public void test() throws JsonProcessingException {
        // 真实的开发一般使用 JSON 来传递对象
        User user = new User();
        user.setName("mianbao");
        user.setAge(18);
        // String jsonUser = new ObjectMapper().writeValueAsString(user);
        // redisTemplate.opsForValue().set("user", jsonUser);
        redisTemplate.opsForValue().set("user", user);
        System.out.println(redisTemplate.opsForValue().get("user"));
    }

对象需要实现Serializable接口

public class User implements Serializable {
    private String name;
    private int age;
}

序列化接口的实现类:

自定义的RedisTempalte

@Configuration
public class RedisConfig {

    // 自定义 redisTemplate 模板
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 我们为了开发方便一般使用 
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // Json 序列化配置
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        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;
    }
}

使用默认的 redisTemplate User在 redis中的内容

127.0.0.1:6379> keys *
1) "xacxedx00x05tx00x04user"

使用自定义的 redisTemplate User在 redis中的内容

127.0.0.1:6379> keys *
1) "user"
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/884634.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号