springboot集成了哪些框架_redis java客户端

springboot集成了哪些框架_redis java客户端Springboot集成Redis添加Redis依赖<depency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!–连接池–>

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

Springboot 集成Redis

添加Redis依赖

       <depency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--连接池-->
         <dependency> 
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

配置文件:

spring:
  redis:
    timeout: 0
    #Redis服务器地址
    host: 127.0.0.1
    #Redis服务器连接端口
    port: 6379
    #Redis服务器连接密码(默认为空)
    password:
  cache:
    redis:
      time-to-live: 60000

自定义RedisTemplate

  @Bean
    @Primary
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { 
   
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setDefaultSerializer(genericJackson2JsonRedisSerializer());

        return template;
    }
    
    private RedisSerializer<Object> genericJackson2JsonRedisSerializer() { 
   
        return new GenericJackson2JsonRedisSerializer(buildMapper());
    }


    private ObjectMapper buildMapper() { 
   
        ObjectMapper objectMapper = new ObjectMapper();

        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        //设置类型
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY);
        //支持java8 时间序列化
        objectMapper.registerModule(new JavaTimeModule());

        //忽略null值
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }

后续使用RedisTemplate<String,Object>操作缓存;

使用注解进行缓存操作涉及CacheManage
RedisCacheManager源码

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisConnectionFactory.class)
@AutoConfigureAfter(RedisAutoConfiguration.class)
@ConditionalOnBean(RedisConnectionFactory.class)
@ConditionalOnMissingBean(CacheManager.class)
@Conditional(CacheCondition.class)
class RedisCacheConfiguration { 
   

	@Bean
	RedisCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers cacheManagerCustomizers,
			ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
			ObjectProvider<RedisCacheManagerBuilderCustomizer> redisCacheManagerBuilderCustomizers,
			RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) { 
   
		RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(
				determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader()));
		List<String> cacheNames = cacheProperties.getCacheNames();
		if (!cacheNames.isEmpty()) { 
   
			builder.initialCacheNames(new LinkedHashSet<>(cacheNames));
		}
		redisCacheManagerBuilderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
		return cacheManagerCustomizers.customize(builder.build());
	}
}

RedisCacheConfiguration 会注入一个RedisCacheManager ,内部使用JDK序列化;如果想使用自己定义的序列化方式,可以提供一个RedisCacheConfiguration bean,或者实现RedisCacheManagerBuilderCustomizer接口,对RedisCacheManagerBuilder进行更改;

提供RedisCacheConfiguration bean

  @Bean
    public RedisCacheConfiguration determineConfiguration(CacheProperties cacheProperties) { 
   
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        // 设置redis中值的序列化方式,方便redisClient可读
        config = config.serializeValuesWith(SerializationPair.fromSerializer(jackson2JsonRedisSerializer())).computePrefixWith(name -> name + ":");//替换掉默认的双冒号
        Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) { 
   
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) { 
   
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) { 
   
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) { 
   
            config = config.disableKeyPrefix();
        }

        return config;
    }

    /** * 使用Jackson序列化器 */
    private RedisSerializer<Object> jackson2JsonRedisSerializer() { 
   
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
                Object.class);

        jackson2JsonRedisSerializer.setObjectMapper(buildMapper());
        return jackson2JsonRedisSerializer;
    }
    
    private ObjectMapper buildMapper() { 
   
        ObjectMapper objectMapper = new ObjectMapper();

        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        //设置类型
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY);
        Set<Object> registeredModuleIds = objectMapper.getRegisteredModuleIds();
        registeredModuleIds.forEach(System.out::println);
        objectMapper.registerModule(new JavaTimeModule());

        //忽略null值
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }

spring-boot-starter-data-redis 会使用RedisAutoConfiguration自动配置:

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
//属性配置
@EnableConfigurationProperties(RedisProperties.class)
//连接配置
@Import({ 
    LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration{ 
   
......
}

2.x版本默认使用lettuce作为客户端;
连接池pool虽然有默认值,但是并不会启用

/** * Pool properties. */
	public static class Pool { 
   

		/** * Maximum number of "idle" connections in the pool. Use a negative value to * indicate an unlimited number of idle connections. */
		private int maxIdle = 8;

		/** * Target for the minimum number of idle connections to maintain in the pool. This * setting only has an effect if both it and time between eviction runs are * positive. */
		private int minIdle = 0;

@Bean
	@ConditionalOnMissingBean(RedisConnectionFactory.class)
	LettuceConnectionFactory redisConnectionFactory(
			ObjectProvider<LettuceClientConfigurationBuilderCustomizer> builderCustomizers,
			ClientResources clientResources) throws UnknownHostException { 
   
//这里的getPool会是null,需要在yml设置一个pool属性才会创建pool对象
		LettuceClientConfiguration clientConfig = getLettuceClientConfiguration(builderCustomizers, clientResources,
				getProperties().getLettuce().getPool());
		return createLettuceConnectionFactory(clientConfig);
	}

springboot注解操作缓存

注解 使用方式
@CacheConfig 作用在类上的配置型注解,cacheNames 设置key前缀, 默认会用::与后面的key拼接,cacheManger 指定缓存使用的cacheManger
@Cacheable 作用在方法上,先获取缓存,缓存没有就执行方法,将方法的返回值缓存起来,eg: @Cacheable(key = “#p0.id”, condition = “#p0.id!=null”) EL表达式参考源码注释
@CachePut 添加缓存:会替换掉现有的缓存 ;eg:@CachePut(key = “#result.id”, unless = “#result==null”)
@CacheEvict 缓存删除, 可以指定删除指定的key,也可以删除全部, 删除缓存的操作默认在方法执行后,通过beforeInvocation设置

所有的注解操作都会涉及CacheManger, 在上下文只有一个CacheManger时会默认使用,否则需要在注解中指明.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/190724.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 如何开发一款游戏:游戏开发流程及所需工具

    如何开发一款游戏:游戏开发流程及所需工具本文来自作者goto先生在GitChat上分享「如何开发一款游戏:游戏开发流程及所需工具」,「阅读原文」查看交流实录。「文末高能」编辑|哈比游戏作为娱乐生活的一个方面,参与其中的人越来越多,而大部分参与其中的人都是以玩家的身份。他们热爱一款游戏,或是被游戏的故事情节、炫丽的场景、动听的音乐所艳羡,亦或是被游戏中角色扮演、炫酷的技能、有趣的任务所吸引,然而他们中的大多数可能并不了解如此

    2022年4月29日
    66
  • rdesktop教程_rdesktop 退出全屏

    rdesktop教程_rdesktop 退出全屏我的配置:1.准备工作:ubuntu端:Windows端:1.计算机属性远程设置远程,勾选:允许远程连接到此计算机;2.远程桌面–允许ubuntu端,执行命令:2.命令解释

    2022年8月4日
    3
  • Java内存管理-探索Java中字符串String(十二)

    做一个积极的人编码、改bug、提升自己我有一个乐园,面向编程,春暖花开!文章目录一、初识String类二、字符串的不可变性三、字符串常量池和 intern 方法四、面试题1、 String s1 = new String(“hello”);这句话创建了几个字符串对象?2、有时候在面试的时候会遇到这样的问题:**都说String是不可变的,为什么我可以这样做呢,String a = “1”…

    2022年2月28日
    32
  • 十大免费代理ip软件_国内静态ip代理软件

    十大免费代理ip软件_国内静态ip代理软件如今,随着网络的快速发展,很多的人对代理IP都已经有了很深入的了解,那么有很多的朋友在使用代理IP的时候也会遇到各种各样的问题,下面就带大家来详细了解下代理IP的使用技巧。1、直接使用代理IP打开Internet选项,通过对局域网的设置来选择LAN代理服务器,其次填写相对应的端口号以及ip地址,填写好之后就可以保存刷新浏览器IP就变更好了,使用这种方法能够解决网站的ip地址限制问题,适合效果补量的业务。2、代理IP的并发不宜过大在使用代理IP时,无论代理IP有没有并发的限制,单个的IP都不能过大.

    2022年4月20日
    900
  • 自动化测试系列(三)|UI测试「建议收藏」

    自动化测试系列(三)|UI测试「建议收藏」UI测试是一种测试类型,也称为用户界面测试,通过该测试,我们检查应用程序的界面是否工作正常或是否存在任何妨碍用户行为且不符合书面规格的BUG。了解用户将如何在用户和网站之间进行交互以执行UI测试至关重要,通过执行UI测试,测试人员将尝试模仿用户的行为,以查看用户将如何与程序进行交互,并查看网站的运行情况是否如预期的那样,是否有缺陷。在上次的自动化测试系列(二)中为大家大体介绍了API测试的概念及在猪齿鱼中的实践展开,本文主要围绕UI测试进行概念介绍及Choerodon中的实践展开。下面.

    2022年10月26日
    0
  • SpringCloud(六)—OpenFeign的执行流程以及配置时需要注意的点

    SpringCloud(六)—OpenFeign的执行流程以及配置时需要注意的点

    2020年11月12日
    359

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号