精选列表

搜索[springboot2],共10000篇文章
优秀的个人博客,低调大师

精通SpringBoot——第七篇:整合Redis实现缓存

项目中用到缓存是很常见的事情, 缓存能够提升系统访问的速度,减轻对数据库的压力等好处。今天我们来讲讲怎么在spring boot 中整合redis 实现对数据库查询结果的缓存。首先第一步要做的就是在pom.xml文件添加spring-boot-starter-data-redis。要整合缓存,必不可少的就是我们要继承一个父类CachingConfigurerSupport。我们先看看这个类的源码 public class CachingConfigurerSupport implements CachingConfigurer { // Spring's central cache manage SPI , @Override @Nullable public CacheManager cacheManager() { return null; } //key的生成策略 @Override @Nullable public KeyGenerator keyGenerator() { return null; } //Determine the Cache instance(s) to use for an intercepted method invocation. @Override @Nullable public CacheResolver cacheResolver() { return null; } //缓存错误处理 @Override @Nullable public CacheErrorHandler errorHandler() { return null; } } RedisConfig类 @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { return new MessageListenerAdapter(receiver, "receiveMessage"); } @Bean Receiver receiver(CountDownLatch latch) { return new Receiver(latch); } @Bean CountDownLatch latch() { return new CountDownLatch(1); } public class Receiver { private CountDownLatch latch; @Autowired public Receiver(CountDownLatch latch) { this.latch = latch; } public void receiveMessage(String message) { latch.countDown(); } } @Bean public KeyGenerator myKeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... objects) { StringBuilder sb = new StringBuilder(); sb.append(o.getClass().getName()); sb.append(method.getName()); for (Object obj : objects) { sb.append(JSON.toJSONString(obj)); } return sb.toString(); } }; } /** * @param redisConnectionFactory * @return * @// TODO: 2018/4/27 redis fastjson序列化 */ @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); //使用fastjson序列化 FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); // 全局开启AutoType,不建议使用 // ParserConfig.getGlobalInstance().setAutoTypeSupport(true); // 建议使用这种方式,小范围指定白名单 ParserConfig.getGlobalInstance().addAccept("com.developlee.models."); // value值的序列化采用fastJsonRedisSerializer template.setValueSerializer(fastJsonRedisSerializer); template.setHashValueSerializer(fastJsonRedisSerializer); // key的序列化采用StringRedisSerializer template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setConnectionFactory(redisConnectionFactory); return template; } @Bean @ConditionalOnMissingBean(StringRedisTemplate.class) public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } /** * @return * @// TODO: 2018/4/27 设置redis 缓存时间 5 分钟 */ @Bean public RedisCacheConfiguration redisCacheConfiguration() { FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class); RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofMinutes(5)); return configuration; } } 这段代码中,重点关注对象是RedisTemplate 和StringRedisTemplate还有RedisMessageListenerContainer,RedisTemplate和StringRedisTemplate设置了一些序列化的参数和指定序列化的范围(主要为了防止黑客利用Redis的序列化漏洞),@ConditionalOnMissingBean注解的意思就是如果容器中没有这个类型Bean就选择当前Bean。RedisMessageListenerContainer是为Redis消息侦听器提供异步行为的容器,主要处理低层次的监听、转换和消息发送的细节。 再来看看application.xml我们的配置 , so easy~~ spring: redis: database: 0 # Redis数据库索引(默认为0) host: 192.168.0.100 # Redis服务器地址 (默认为127.0.0.1) port: 6379 # Redis服务器连接端口 (默认为6379) password: 123456 # Redis服务器连接密码(默认为空) timeout: 2000 # 连接超时时间(毫秒) cache: type: redis 接下来我们就可以使用Redis缓存了,在Service层我们用注解@Cacheable来缓存查询的结果。 @Cacheable(value= "orderDetailCache", keyGenerator = "myKeyGenerator", unless = "#result eq null") public OrderDetailEntity findOrderDetail(OrderDetailEntity orderDetailEntity) { return orderDetailDao.findEntity(orderDetailEntity); } 到这里我们就已经整合了Redis缓存了,是不是很简单的呢?自己多动手尝试哦! 最后,以上示例代码可在我的github.com中找到。我的个人公众号:developlee的潇洒人生。关注了也不一定更新,更新就不得了了。

优秀的个人博客,低调大师

SpringBoot开发案例之整合定时任务(Scheduled)

来来来小伙伴们,基于上篇的邮件服务,定时任务就不单独分项目了,天然整合进了邮件服务中。 不知道,大家在工作之中,经常会用到那些定时任务去执行特定的业务,这里列举一下我在工作中曾经使用到的几种实现。 任务介绍 Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。Timer的优点在于简单易用;缺点是Timer的所有任务都是由同一个线程调度的,因此所有任务都是串行执行的。同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务,不过这种实现已经被项目所废弃。 开源集群任务框架Quartz,这是一个功能比较强大的的调度器,适合做任务集群,解决单点故障,目前项目中在使用。 Spring家族自带的Scheduled,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多,适用于简单的任务,微服务使用很方便。 项目应用 创建任务 代码中,可以发现,sendMail方法上注解被注释掉了,目前我们采用的是xml配置实现的。 import org.springframework.stereotype.Component; /** * 统计失败邮件定时重新发送 * 创建者 科帮网 * 创建时间 2017年7月21日 * */ @Component("sendMail") public class SendMail { //@Scheduled(cron = "0/5 * * * * ?") public void sendMail() { System.out.println("统计失败邮件定时重新发送开始"); } } 配置文件 <!-- 配置任务线性池 --> <task:executor id="executor" pool-size="5" /> <task:scheduler id="scheduler" pool-size="5"/> <!-- 启用注解驱动的定时任务 --> <task:annotation-driven executor="executor" scheduler="scheduler" proxy-target-class="true"/> <task:scheduled-tasks scheduler="scheduler"> <!-- 统计失败邮件定时重新发送 --> <task:scheduled ref="sendMail" method="sendMail" cron="0/5 * * * * ?"/> </task:scheduled-tasks> 启动项目 /** * 启动类 * 创建者 科帮网 * 创建时间 2017年7月19日 * */ @EnableAutoConfiguration @ComponentScan(basePackages={"com.itstyle.main"}) @ImportResource({"classpath:spring-context-dubbo.xml","classpath:spring-context-task.xml"}) public class Application { private static final Logger logger = Logger.getLogger(Application.class); public static void main(String[] args) throws InterruptedException { SpringApplication.run(Application.class, args); logger.info("项目启动 "); } } 启动后,控制台会每5s打印"统计失败邮件定时重新发送开始"。当然Scheduled的功能不仅仅如此,我们查找源码Scheduled类,可以发现还有一些注解属性,这里就不一一为大家介绍了。总之,要养成查看源码API的习惯。 @Target({ java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Repeatable(Schedules.class) public @interface Scheduled { public abstract String cron(); public abstract String zone(); public abstract long fixedDelay(); public abstract String fixedDelayString(); public abstract long fixedRate(); public abstract String fixedRateString(); public abstract long initialDelay(); public abstract String initialDelayString(); } 项目:http://git.oschina.net/52itstyle/spring-boot-mail 作者: 小柒 出处: https://blog.52itstyle.com 本文版权归作者和云栖社区所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 如有问题, 可邮件(345849402@qq.com)咨询。

资源下载

更多资源
优质分享Android(本站安卓app)

优质分享Android(本站安卓app)

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario,低调大师唯一一个Java游戏作品

Mario,低调大师唯一一个Java游戏作品

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Oracle Database,又名Oracle RDBMS

Oracle Database,又名Oracle RDBMS

Oracle Database,又名Oracle RDBMS,或简称Oracle。是甲骨文公司的一款关系数据库管理系统。它是在数据库领域一直处于领先地位的产品。可以说Oracle数据库系统是目前世界上流行的关系数据库管理系统,系统可移植性好、使用方便、功能强,适用于各类大、中、小、微机环境。它是一种高效率、可靠性好的、适应高吞吐量的数据库方案。

Java Development Kit(Java开发工具)

Java Development Kit(Java开发工具)

JDK是 Java 语言的软件开发工具包,主要用于移动设备、嵌入式设备上的java应用程序。JDK是整个java开发的核心,它包含了JAVA的运行环境(JVM+Java系统类库)和JAVA工具。