<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-cacheartifactId>
dependency>
@SpringBootApplication
//开启缓存功能
@EnableCaching
public class Springboot19CacheApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot19CacheApplication.class, args);
}
}
@Cacheable(value = "cacheSpace", key = "#id")
public Book getById(Integer id) {
return bookDao.selectById(id);
}
Ehcache
Redis
memcached
<dependency>
<groupId>net.sf.ehcachegroupId>
<artifactId>ehcacheartifactId>
dependency>
spring:
cache:
type: ehcache
ehcarche:
config: ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="D:\ehcache" />
<defaultCache
eternal="false"
diskPersistent="false"
maxElementsInMemory="1000"
overflowToDisk="false"
timeToIdleSeconds="60"
timeToLiveSeconds="60"
memoryStoreEvictionPolicy="LRU" />
<cache
name="smsCode"
eternal="false"
diskPersistent="false"
maxElementsInMemory="1000"
overflowToDisk="false"
timeToIdleSeconds="10"
timeToLiveSeconds="10"
memoryStoreEvictionPolicy="LRU" />
ehcache>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
Spring:
redis:
host: localhost
port: 6379
cache:
type: redis
redis:
use-key-prefix: true #是否使用前缀名(系统定义前缀名)
cache-null-values: false #是否允许空值
key-prefix: aa #追加自定义前缀名
time-to-live: 10s #有效时间
memcached.exe -d install
memcached.exe -d start
♦ 停止服务
memcached.exe -d stop
memcached客户端选择
♦ Memcached Client for Java:最早期客户端,稳定可靠,用户群广
♦ SpyMemcached:效率更高
♦ Xmemcached:并发处理更好
SpringBoot未提供对memcached的整合,需要使用硬编码方式实现客户端初始化管理
加入Xmemcache坐标(缓存供应商实现)
<dependency>
<groupId>com.googlecode.xmemcachedgroupId>
<artifactId>xmemcachedartifactId>
<version>2.4.7version>
dependency>
memcached:
# memcache服务器地址
servers: localhost:11211
# 连接池的数量
poolSize: 10
# 设置默认操作超时
opTimeout: 3000
@Component
@ConfigurationProperties(prefix = "memcached")
@Data
public class XMemcachedProperties {
private String servers;
private int poolSize;
private long opTimeout;
}
@Configuration
public class XMemcachedConfig {
@Autowired
private XMemcachedProperties memcachedProperties;
@Bean
public MemcachedClient getMemcachedClient() throws IOException {
MemcachedClientBuilder memcachedClientBuilder = new XMemcachedClientBuilder(memcachedProperties.getServers());
memcachedClientBuilder.setConnectionPoolSize(memcachedProperties.getPoolSize());
memcachedClientBuilder.setOpTimeout(memcachedClientBuilder.getOpTimeout());
MemcachedClient memcachedClient = memcachedClientBuilder.build();
return memcachedClient;
}
}
@RestController
@RequestMapping("/sms")
public class SMSCodeController {
@Autowired
private MemcachedClient memcachedClient;
@GetMapping
public String getCode(String tele) {
String code = smsCodeService.sendCodeToSMS(tele);
//将数据加入memcache
try {
memcachedClient.set(tele, 10, code);
} catch (Exception e) {
}
return code;
}
@PostMapping
public boolean checkCode(SMSCode smsCode) {
String code = null;
try {
code = memcachedClient.get(smsCode.getTele()).toString();
} catch (Exception e) {
e.printStackTrace();
}
return smsCode.getCode().equals(code);
}
}
<dependency>
<groupId>com.alicp.jetcachegroupId>
<artifactId>jetcache-starter-redisartifactId>
<version>2.6.4version>
dependency>
远程
缓存必要属性jetcache:
remote:
default:
type: redis
host: localhost
port: 6379
poolConfig:
maxTotal: 50
sms:
type: redis
host: localhost
port: 6379
poolConfig:
maxTotal: 50
本地
缓存必要属性jetcache:
local:
default:
type: linkedhashmap
keyConvertor: fastjson
jetcache:
statIntervalMinutes: 15
areaInCacheName: false
local:
default:
type: linkedhashmap
keyConvertor: fastjson
limit: 100
remote:
default:
host: localhost
port: 6379
type: redis
keyConvertor: fastjson
valueEncoder: java
valueDecoder: java
poolConfig:
minIdle: 5
maxIdle: 20
maxTotal: 50
属性 | 默认值 | 说明 |
---|---|---|
jetcache.statIntervalMinutes | 0 | 统计间隔,0表示不统计 |
jetcache.hiddenPackages | 无 | 自动生成name时,隐藏指定的包名前缀 |
jetcache.[local|remote].${area}.type | 无 | 缓存类型,本地支持linkedhashmap、caffeine,远程支持redis、tair |
jetcache.[local|remote].${area}.keyConvertor | 无 | key转换器,当前仅支持fastjson |
jetcache.[local|remote].${area}.valueEncoder | java | 仅remote类型的缓存需要指定,可选java和kryo |
jetcache.[local|remote].${area}.valueDecoder | java | 仅remote类型的缓存需要指定,可选java和kryo |
jetcache.[local|remote].${area}.limit | 100 | 仅local类型的缓存需要指定,缓存实例最大元素数 |
jetcache.[local|remote].${area}.expireAfterWritelnMillis | 无穷大 | 默认过期时间,毫秒单位 |
jetcache.local.${area}.expireAfterWritelnMillis | 0 | 仅local类型的缓存有效,毫秒单位,最大不活动间隔 |
@SpringBootApplication
//jetCache启用缓存的主开关
@EnableCreateCacheAnnotation
public class Springboot20CacheApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot20CacheApplication.class, args);
}
}
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
@Autowired
private CodeUtils codeUtils;
@CreateCache(name = "jetCache_", expire = 1000, timeUnit = TimeUnit.SECONDS, cacheType = CacheType.LOCAL)
private Cache<String, String> jetCache;
}
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
@Override
public String sendCodeToSMS(String tele) {
String code = codeUtils.generator(tele);
jetCache.put(tele, code);
return code;
}
@Override
public boolean checkCode(SMSCode smsCode) {
String code = jetCache.get(smsCode.getTele());
return smsCode.getCode().equals(code);
}
}
@SpringBootApplication
//jetCache启用缓存的主开关
@EnableCreateCacheAnnotation
//开启方法注解缓存
@EnableMethodCache(basePackages = "com.itheima")
public class Springboot20CacheApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot20CacheApplication.class, args);
}
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
@Cached(name = "book_", key = "#id", expire = 3600, cacheType = CacheType.LOCAL)
//@CacheRefresh(refresh = 10)
public Book getById(Integer id) {
return bookDao.selectById(id);
}
@Override
@CacheUpdate(name = "book_", key = "#book.id", value = "#book")
public boolean update(Book book) {
return bookDao.updateById(book) > 0;
}
@Override
@CacheInvalidate(name = "book_", key = "#id")
public boolean delete(Integer id) {
return bookDao.deleteById(id) > 0;
}
}
@Data
public class Book implements Serializable {
}
jetcache:
remote:
default:
host: localhost
port: 6379
keyConvertor: fastjson
valueEncode: java
valueDecode: java
type: redis
jetcache:
statIntervalMinutes: 1
<dependency>
<groupId>net.oschina.j2cachegroupId>
<artifactId>j2cache-coreartifactId>
<version>2.8.5-releaseversion>
dependency>
<dependency>
<groupId>net.oschina.j2cachegroupId>
<artifactId>j2cache-spring-boot2-starterartifactId>
<version>2.8.0-releaseversion>
dependency>
<dependency>
<groupId>net.sf.ehcachegroupId>
<artifactId>ehcacheartifactId>
dependency>
j2cache:
config-location: j2cache.properties
# 配置1级缓存
j2cache.L1.provider_class=ehcache
ehcache.configXml=ehcache.xml
# 设置是否启用2级缓存
j2cache.l2-cache-open = false
# 配置1级缓存数据到2级h缓存的广播方式:可以使用redis提供的消息订阅模式,也可以使用jgroups多播实现
j2cache.broadcast=net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy
# 配置2级缓存
j2cache.L2.provider_class=net.oschina.j2cache.cache.support.redis.SpringRedisProvider
j2cache.L2.config_section=redis
redis.hosts=localhost:6379
redis.mode=single
redis.namespace=j2cache
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
@Autowired
private CodeUtils codeUtils;
@Autowired
private CacheChannel cacheChannel;
@Override
public String sendCodeToSMS(String tele) {
String code = codeUtils.generator(tele);
cacheChannel.set("sms", tele, code);
return code;
}
@Override
public boolean checkCode(SMSCode smsCode) {
String code = cacheChannel.get("sms", smsCode.getTele()).asString();
return smsCode.getCode().equals(code);
}
}
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-quartzartifactId>
dependency>
QuartzJobBean
public class MyQuartz extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
System.out.println("quartz task run...");
}
}
@Configuration
public class QuartzConfig {
@Bean
public JobDetail printJobDetail() {
//绑定具体的工作
return JobBuilder.newJob(MyQuartz.class).storeDurably().build();
}
@Bean
public Trigger printJobTrigger() {
ScheduleBuilder schedBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
//绑定对应的工作明细
return TriggerBuilder.newTrigger().forJob(printJobDetail()).withSchedule(schedBuilder).build();
}
}
@SpringBootApplication
//开启定时任务功能
@EnableScheduling
public class Springboot22TaskApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot22TaskApplication.class, args);
}
}
@Component
public class MyBean {
@Scheduled(cron = "0/1 * * * * ?")
public void print() {
System.out.println("spring task run.");
}
}
spring:
task:
scheduling:
# 任务调度线程池大小 默认1
pool:
size: 1
# 调度线程名称前缀 默认scheduling-
thread-name-prefix: ssm_
shutdown:
# 线程池关闭时等待所有任务完成
await-termination: false
# 调度线程关闭前最大等待时间,确保最后一定关闭
await-termination-period: 10s
SMTP(Simple Mail Transfer Protocol):简单邮件传输协议,用于发送
电子邮件的传输协议
POP3(Post Office Protocol - Version 3): 用于接收
电子邮件的标准协议
IMAP(Internet Mail Access Protocol):互联网消息协议,是POP3的替代协议
导入SpringBoot整合JavaMail坐标
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-mailartifactId>
dependency>
dependencies>
spring:
mail:
host: smtp.qq.com
username: ****353464@qq.com
password: *********
@Service
public class SendMailServiceImpl implements SendMailService {
@Autowired
private JavaMailSender javaMailSender;
//发送人
private String from = "[email protected]";
//接收人
private String to = "[email protected]";
//标题
private String subject = "测试邮件";
//正文
private String context = "测试邮件正文内容";
@Override
public void sendMail() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from + "(小甜甜)");
message.setTo(to);
message.setSubject(subject);
message.setText(context);
javaMailSender.send(message);
}
}
三种异步消息传递技术
pub
lish-sub
scribe:发布订阅模型,消息可以被多个消费者消费,生产者和消费者完全独立,不需要感知对方的存在BytesMessage
direct
exchangetopic
exchangeactivemq.bat
http://127.0.0.1:8161/
♦ 服务器端口:61616,管理后台端口:8161
♦ 用户名&密码:admin
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-activemqartifactId>
dependency>
spring:
activemq:
broker-url: tcp://localhost:61616
jms:
template:
default-destination: itheima
pub-sub-domain: true
@Service
public class MessageServiceActivemqImpl implements MessageService {
@Autowired
private JmsMessagingTemplate messageTemplate;
@Override
public void sendMessage(String id) {
System.out.println("待发送短信的订单已纳入处理的队列,id:" + id);
messageTemplate.convertAndSend("order.queue.id:", id);
}
@Override
public String doMessage() {
String id = messageTemplate.receiveAndConvert("order.queue.id:", String.class);
System.out.println("已完成短信发送业务,id" + id);
return id;
}
}
@Component
public class MessageListener {
@JmsListener(destination = "order.queue.id:")
@SendTo("order.other.queue.id:")
public String receive(String id) {
System.out.println("已完成短信发送业务,id" + id);
return "new:" + id;
}
}
RabbitMQ基于Erlang语言编写,需要安装Erlang
Erlang
♦ 安装:一键安装,安装完毕需要重启,需要依赖windows组件
环境变量配置
♦ ERLANG_HOME
♦ PATH
启动服务
rabbitmq-service.bat start
rabbitmq-service.bat stop
rabbitmqctl status
rabbitmq-plugins.bat list
♦ 开启服务管理插件
rabbitmq-plugins.bat enable rabbitmq_management
♦ 访问服务器
http://localhost:15672
□ 服务端口:5672,管理后台端口:15672
□ 用户名&密码:guest
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-amqpartifactId>
dependency>
spring:
rabbitmq:
host: localhost
port: 5672
@Configuration
public class RabbitConfigDirect {
@Bean
public Queue directQueue() {
// durable:是否持久化,默认false
// exclusive:是否当前连接专用,默认false,连接关闭后队列即被删除
// autoDelete:是否自动删除,当生产者或消费者不再使用此队列,自动给删除
return new Queue("direct_queue",true,false,false);
}
@Bean
public Queue directQueue2() {
return new Queue("direct_queue2");
}
@Bean
public DirectExchange directExchange() {
return new DirectExchange("directExchange");
}
@Bean
public Binding bindingDirect() {
return BindingBuilder.bind(directQueue()).to(directExchange()).with("direct");
}
@Bean
public Binding bindingDirect2() {
return BindingBuilder.bind(directQueue2()).to(directExchange()).with("direct2");
}
}
@Service
public class MessageServiceRabbitmqDirectImpl implements MessageService {
@Autowired
private AmqpTemplate amqpTemplate;
@Override
public void sendMessage(String id) {
System.out.println("待发送短信的订单已纳入处理的队列(rabbitmq direct),id:" + id);
amqpTemplate.convertAndSend("directExchange", "direct", id);
}
}
@Component
public class MessageListener {
@RabbitListener(queues = "direct_queue")
public void receive(String id) {
System.out.println("已完成短信发送业务(RabbitMQ direct),id" + id);
}
}
@Configuration
public class RabbitConfigTopic {
@Bean
public Queue topicQueue() {
return new Queue("topic_queue");
}
@Bean
public Queue topicQueue2() {
return new Queue("topic_queue2");
}
@Bean
public TopicExchange topicExchange() {
return new TopicExchange("topicExchange");
}
@Bean
public Binding bindingTopic() {
return BindingBuilder.bind(topicQueue()).to(topicExchange()).with("topic.*.id");
}
@Bean
public Binding bindingTopic2() {
return BindingBuilder.bind(topicQueue2()).to(topicExchange()).with("topic.orders.*");
}
}
匹配键 | topic.*.* | topic.# |
---|---|---|
topic.order.id | true | true |
order.topic.id | false | false |
topic.sm.order.id | false | true |
topic.sm.id | false | true |
topic.id.order | true | true |
topic.id | false | true |
topic.order | false | true |
@Service
public class MessageServiceRabbitmqDirectImpl implements MessageService {
@Autowired
private AmqpTemplate amqpTemplate;
@Override
public void sendMessage(String id) {
System.out.println("待发送短信的订单已纳入处理的队列(rabbitmq topic),id:" + id);
amqpTemplate.convertAndSend("topicExchange", "topic.orders.id", id);
}
}
@Component
public class MessageListener {
@RabbitListener(queues = "topic_queue")
public void receive(String id) {
System.out.println("已完成短信发送业务(RabbitMQ topic 1),id" + id);
}
@RabbitListener(queues = "topic_queue")
public void receive2(String id) {
System.out.println("已完成短信发送业务(RabbitMQ topic 2),id" + id);
}
}
默认服务器端口:9876
环境变量配置
♦ ROCKETMQ_HOME
♦ PATH
♦ NAMESRV_ADDR(建议):127.0.0.1:9876
命名服务器与broker
先启动NAMESERVER:start mqnamesrv.cmd
然后启动BROKER:start mqbroker.cmd -n 127.0.0.1:9876 autoCreateTopicEnable=true
(备注:autoCreateTopicEnable=true 表示可以动态创建topic)
tools.cmd org.apache.rocketmq.example.quickstart.Producer
tools.cmd org.apache.rocketmq.example.quickstart.Consumer
<dependency>
<groupId>org.apache.rocketmqgroupId>
<artifactId>rocketmq-spring-boot-starterartifactId>
<version>2.2.2version>
dependency>
rocketmq:
name-server: 127.0.0.1:9876
producer:
group: group_rocketmq
@Service
public class MessageServiceRocketmqImpl implements MessageService {
@Autowired
private RocketMQTemplate rocketMQTemplate;
@Override
public void sendMessage(String id) {
System.out.println("待发送短信的订单已纳入处理的队列(rocketmq direct),id:" + id);
//rocketMQTemplate.convertAndSend("order_id", id);
SendCallback callback = new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
System.out.println("消息发送成功");
}
@Override
public void onException(Throwable throwable) {
System.out.println("消息发送失败");
}
};
rocketMQTemplate.asyncSend("order_id",id,callback);
}
}
@Component
@RocketMQMessageListener(topic = "order_id",consumerGroup = "group_rocketmq")
public class MessageListener implements RocketMQListener<String> {
@Override
public void onMessage(String id) {
System.out.println("已完成短信发送业务(RocketMQ),id" + id);
}
}
zookeeper-server-start.bat ../../config/zookeeper.properites
♦ 默认端口:2181
kafka-server-start.bat ../../config/server.properties
♦ 默认端口:9092
kafka-topics.bat --zookeeper 127.0.0.1:2181 --create --replication-factor 1 --partitions 1 --topic itheima
kafka-topics.bat --zookeeper 127.0.0.1:2181 --list
kafka-topics.bat --zookeeper 127.0.0.1:2181 --delete --topic itheima
kafka-console-producer.bat --broker-list localhost:9092 --topic itheima2022
kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic itheima2022 --from-beginning
<dependency>
<groupId>org.springframework.kafkagroupId>
<artifactId>spring-kafkaartifactId>
dependency>
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: order
@Service
public class MessageServiceKafkalmpl implements MessageService {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Override
public void sendMessage(String id) {
System.out.println("待发送短信的订单已纳入处理的队列(kafka),id:" + id);
kafkaTemplate.send("itheima2022", id);
}
}
@Component
public class MessageServiceKafkaImpl {
@KafkaListener(topics = {"itheima2022"})
void onMessage(ConsumerRecord<String, String> record) {
System.out.println("已完成短信发送业务(kafka),id" + record.value());
}
}