1、定时工作
/**
- 定时工作
- 长处:简单易行,反对集群操作
- 毛病:(1)对服务器内存耗费大
- (2)存在提早,比方你每隔3分钟扫描一次,那最坏的延迟时间就是3分钟
- (3)数据量大,每隔几分钟这样扫描一次,数据库损耗极大
*/
public class MyJob implements Job {
public void execute(JobExecutionContext jobExecutionContext)
throws JobExecutionException {
System.out.println("进入数据库");
}
public static void main(String[] args) throws SchedulerException {
// 创立工作
JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
.withIdentity("job1","group1").build();
// 创立触发器Trigger 每三秒执行一次
Trigger trigger= TriggerBuilder
.newTrigger()
.withIdentity("trigger1", "group3")
.withSchedule(
SimpleScheduleBuilder
.simpleSchedule()
.withIntervalInSeconds(3)
.repeatForever()
) .build();
/**
- 创立和初始化Quartz Scheduler调度工厂
- 调用工厂中的getScheduler()将生成调度程序
*/
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
// 将工作及其触发器放入调度器
scheduler.scheduleJob(jobDetail,trigger);
// 调度器开始调度工作
scheduler.start();
}
}
2、提早队列
/**
- 提早队列
- JDK自带的DelayQueue来实现,
- 这是一个无界阻塞队列,
- 该队列只有在提早期满的时候能力从中获取元素,
- 放入DelayQueue中的对象,是必须实现Delayed接口的。
- 长处:效率高,工作触发时间延迟低。
- 毛病:
- (1)服务器重启后,数据全副隐没,怕宕机
- (2)集群扩大相当麻烦
- (3)因为内存条件限度的起因,比方下单未付款的订单数太多,那么很容易就呈现OOM异样
- (4)代码复杂度较高
*/
public class OrderDelay implements Delayed {
private String orderId;
private Long timeout; OrderDelay(String orderId, Long timeout) {
this.orderId = orderId;
this.timeout = timeout + System.nanoTime(); }
/**
- 用于提早队列外部的比拟排序 以后工夫的延迟时间-比拟对象的延迟时间
- @param other
- @return
*/
public int compareTo(Delayed other) {
if(other == this) {
return 0;
}
OrderDelay t = (OrderDelay) other;
Long d = (getDelay(TimeUnit.NANOSECONDS) - t
.getDelay(TimeUnit.NANOSECONDS));
return (d == 0) ? 0 : ((d < 0) ? -1 : 1); }
/**
- 返回间隔你自定义的超时工夫还有多久
- 取得延迟时间 过期工夫-以后工夫
- @param unit
- @return
*/
public long getDelay(TimeUnit unit) {
return unit.convert(
timeout - System.nanoTime(),
TimeUnit.NANOSECONDS); }
void print() {
System.out.println(orderId + "开始启动了");
}
}
3、工夫轮算法
package wheeltime;
import io.netty.util.*;
import io.netty.util.TimerTask;
import java.util.concurrent.*;
/**
- Netty的HashedWheelTimer来实现
- <p>
- 长处:效率高,工作触发时间延迟工夫比delayQueue低,代码复杂度比delayQueue低。
- 毛病:
- (1)服务器重启后,数据全副隐没,怕宕机
- (2)集群扩大相当麻烦
- (3)因为内存条件限度的起因,比方下单未付款的订单数太多,那么很容易就呈现OOM异样
*/
public class HashedWheelTimerTest {
static class MyTimerTask implements TimerTask { boolean flag; public MyTimerTask(boolean flag) { this.flag = flag; } public void run(Timeout timeout) throws Exception { System.out.println("要去删除了。。。"); this.flag = false; }}public static void main(String[] argv) { MyTimerTask timerTask = new MyTimerTask(true); Timer timer = new HashedWheelTimer(); //轮数,工夫,工夫单位 timer.newTimeout(timerTask, 5, TimeUnit.SECONDS); int i = 1; while(timerTask.flag) { try { Thread.sleep(1000); } catch(InterruptedException e) { e.printStackTrace(); } System.out.println(i + "过来了"); i++; }}
}
4、Redis缓存
形式一:
利用redis的zset,zset是一个有序汇合,每一个元素(member)都关联了一个score,通过score排序来取汇合中的值
利用redis命令了解思路
增加单个元素
redis> ZADD page_rank 10 google.com
(integer) 1
增加多个元素
redis> ZADD page_rank 9 baidu.com 8 bing.com
(integer) 2
redis> ZRANGE page_rank 0 -1 WITHSCORES
1) "bing.com"
2) "8"
3) "baidu.com"
4) "9"
5) "google.com"
6) "10"
查问元素的score值
redis> ZSCORE page_rank bing.com
"8"
移除单个元素
redis> ZREM page_rank google.com
(integer) 1
redis> ZRANGE page_rank 0 -1 WITHSCORES
1) "bing.com"
2) "8"
3) "baidu.com"
4) "9"
java实现:
package timestop.redisout;
import redis.clients.jedis.*;
import java.util.*;
/**
- 利用redis缓存
- 毛病:高并发条件下,多消费者会取到同一个订单号
- 改良:
- (1)用分布式锁,然而用分布式锁,性能降落了,该计划不细说。
- (2)对ZREM的返回值进行判断,只有大于0的时候,才生产数据,于是将consumerDelayMessage()办法里的
*/
public class AppTest {
private static final String ADDR = "127.0.0.1";private static final int PORT = 6379;//JedisPool 创立线程平安的网络连接池private static JedisPool JedisPool = new JedisPool(ADDR, PORT);//获取连接池的一个jedis对象public static Jedis getJedis() { return JedisPool.getResource();}// 生产者, 生成5个订单放进去public void productionDelayMessage() { for(int i = 0; i < 5; i++) { /** * 设置时间延迟3秒 * Calendar.getInstance() * 取一个Calendar对象并能够进行工夫的计算,时区的指定 */ Calendar cal1 = Calendar.getInstance(); //Calendar.SECOND工夫单位,amount工夫数 cal1.add(Calendar.SECOND, 3); //cal1.getTimeInMillis()用于返回此日历的以后工夫 (以毫秒为单位)。 int second3later = (int) (cal1.getTimeInMillis() / 1000); //getJedis().zadd增加元素 AppTest.getJedis().zadd("OrderId", second3later, "OID0000001" + i); System.out.println(System.currentTimeMillis() + "ms:redis生成了一个订单工作:订单ID为\"+\"OID0000001" + i); }}// 消费者, 取订单public void consumerDelayMessage() { Jedis jedis = AppTest.getJedis(); while(true) { //返回有序汇合中指定分数区间的成员列表。 Set<Tuple> items = jedis.zrangeWithScores("OrderId", 0, 1); if(items == null || items.isEmpty()) { System.out.println("以后没有期待的工作"); try { Thread.sleep(500); } catch(InterruptedException e) { e.printStackTrace(); } continue; } int score = (int) ((Tuple) items.toArray()[0]).getScore(); /** * Calendar.getInstance() * 取一个Calendar对象并能够进行工夫的计算,时区的指定 */ Calendar cal = Calendar.getInstance(); //cal1.getTimeInMillis()用于返回此日历的以后工夫 (以毫秒为单位)。 int nowSecond = (int) (cal.getTimeInMillis() / 1000); //原版 有多个线程生产同一个资源的状况 //if(nowSecond >= score) { // String orderId = ((Tuple) items.toArray()[0]).getElement(); // jedis.zrem("OrderId", orderId); // System.out.println(System.currentTimeMillis() + "ms:redis生产了一个工作:生产的订单OrderId为" + orderId); //} //改良后 if(nowSecond >= score) { String orderId = ((Tuple) items.toArray()[0]).getElement(); Long num = jedis.zrem("OrderId", orderId); if(num != null && num > 0) { System.out.println(System.currentTimeMillis() + "ms:redis生产了一个工作:生产的订单OrderId为" + orderId); } } }}public static void main(String[] args) { AppTest appTest = new AppTest(); appTest.productionDelayMessage(); appTest.consumerDelayMessage();}
}
形式二:
该计划应用redis的Keyspace Notifications,中文翻译就是键空间机制,就是利用该机制能够在key生效之后,提供一个回调,实际上是redis会给客户端发送一个音讯。是须要redis版本2.8以上。 实现二 在redis.conf中,退出一条配置 notify-keyspace-events Ex
public class RedisTest {
private static final String ADDR = "127.0.0.1";private static final int PORT = 6379;private static JedisPool jedis = new JedisPool(ADDR, PORT);private static RedisSub sub = new RedisSub();public static void init() { new Thread(new Runnable() { public void run() { jedis.getResource().subscribe(sub, "__keyevent@0__:expired"); } }).start();}public static void main(String[] args) throws InterruptedException { init(); for(int i =0;i<10;i++){ String orderId = "OID000000"+i; jedis.getResource().setex(orderId, 3, orderId); System.out.println(System.currentTimeMillis()+"ms:"+orderId+"订单生成"); }}static class RedisSub extends JedisPubSub { <ahref='http://www.jobbole.com/members/wx610506454'>@Override</a> public void onMessage(String channel, String message) { System.out.println(System.currentTimeMillis()+"ms:"+message+"订单勾销"); }}
}