生产者/消费者模式不在23种常用设计模式里面,但在实际工作中也经常会用到。特别是需要将数据的生产者和消费者解耦,或者用多线程优化性能时都可以派上用场。
一、代码目录结构
目录说明:
- config:Swagger配置,方便通过swagger调用接口测试.
- constant: 枚举常量定义。
- model:模型定义。
- rest: restful接口定义。
- service: 实现业务逻辑。
二、核心代码说明
1. EnumTaskEndType
定义了几种常用的任务结束方式:
package com.elon.constant;
/**
* 任务结束方式
*
* @author elon
* @version 1.0
*/
public enum EnumTaskEndType {
/**
* 无效类型
*/
NA,
/**
* 任务完成结束
*/
COMPLETE,
/**
* 任务被终止结束
*/
TERMINATE;
}
2.Task
定义任务模型,这个是生产者消费者核心模型,包含哪些数据根据具体的业务要求来定义.
package com.elon.model;
import com.alibaba.fastjson.JSONObject;
import com.elon.constant.EnumTaskEndType;
/**
* 任务模型. 任务模型中存储生产者和消费者沟通信息. 具体存储什么信息根据实际的业务来。
*
* @author elon
* @version 1.0
*/
public class Task {
/**
* 任务名称
*/
private String taskName = "";
/**
* 任务结束方式(此字段用于标识任务是否为毒丸任务)
*/
private EnumTaskEndType taskEndType = EnumTaskEndType.NA;
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public EnumTaskEndType getTaskEndType() {
return taskEndType;
}
public void setTaskEndType(EnumTaskEndType taskEndType) {
this.taskEndType = taskEndType;
}
public String toString() {
return JSONObject.toJSONString(this);
}
}
3. ProduceConsumerController
生产者消费者接口层,用于定义rest接口。方便自测试.
package com.elon.rest;
import com.elon.service.ProConsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/v1/produce-consumer")
@Api(tags = "生产者消费者服务")
public class ProduceConsumerController {
@PostMapping("/start-task/{taskAmount}")
@ApiOperation(value = "启动服务任务")
public String startTask(@PathVariable("taskAmount") int taskAmount) {
ProConsService proConsService = new ProConsService();
proConsService.startTask(taskAmount);
return "";
}
}
4. Consumer
消费者。负责任务处理。消费者收到毒丸任务后将毒丸放回队列头( 目的是为了让其它消费者也能尽快收到毒丸结束整个任务),然后退出线程。
package com.elon.service;
import com.elon.constant.EnumTaskEndType;
import com.elon.model.Task;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
/**
* 消费者类. 负责从队列中取出任务消费.
*
* @author elon
* @version 1.0
*/
public class Consumer implements Runnable {
private static final Logger LOGGER = LogManager.getLogger(Consumer.class);
/**
* 阻塞队列
*/
private LinkedBlockingDeque<Task> blockingDeque = null;
public Consumer(LinkedBlockingDeque<Task> blockingDeque) {
this.blockingDeque = blockingDeque;
}
@Override
public void run() {
while (true) {
try {
Task task = blockingDeque.take();
// 收到毒丸任务将毒丸放回队列头,结束当前线程.
if (task.getTaskEndType() != EnumTaskEndType.NA) {
LOGGER.info("收到毒丸任务.{}", task);
blockingDeque.offerFirst(task, 2, TimeUnit.MILLISECONDS);
break;
}
// 消费任务. 这里可以写实际的业务逻辑.
LOGGER.info("消费任务:{}", task);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
LOGGER.info("消费者结束消费.");
}
}
5. Producer
生产者,负责将生产任务放入队列。生产者在生产完所有正常的数据处理任务后,在队列尾放入一个毒丸任务,使消费者线程在处理完所有任务后能退出线程,避免无限等待。
package com.elon.service;
import com.elon.constant.EnumTaskEndType;
import com.elon.model.Task;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
/**
* 生产者类. 负责创建任务放到阻塞队列.
*
* @author elon
* @version 1.0
*/
public class Producer implements Runnable {
private static final Logger LOGGER = LogManager.getLogger(Producer.class);
private LinkedBlockingDeque<Task> blockingDeque = null;
private final int taskAmount;
public Producer(LinkedBlockingDeque<Task> blockingDeque, int taskAmount) {
this.blockingDeque = blockingDeque;
this.taskAmount = taskAmount;
}
@Override
public void run() {
for (int i = 1; i <= taskAmount; ++i) {
try {
Task task = new Task();
task.setTaskName("任务:" + i);
blockingDeque.offer(task, 2, TimeUnit.MILLISECONDS);
LOGGER.info("生产任务:{}", task);
} catch (InterruptedException e) {
LOGGER.error("创建任务异常.", e);
}
}
// 放入毒丸任务已结束消费者线程
try {
Task task = new Task();
task.setTaskName("任务处理结束毒丸");
task.setTaskEndType(EnumTaskEndType.COMPLETE);
blockingDeque.offer(task, 2, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
6. ProConsService
负责生产者和消费者线程初始化.
package com.elon.service;
import com.elon.model.Task;
import java.util.concurrent.LinkedBlockingDeque;
/**
* 生产者消费者服务。启动生产者消费者线程.
*
* @author elon
* @version 1.0
*/
public class ProConsService {
private LinkedBlockingDeque<Task> blockingDeque = new LinkedBlockingDeque<>();
/**
* 开始任务.
*
* @param taskAmount 生产的任务数量
* @author elon
*/
public void startTask(int taskAmount) {
Producer producer = new Producer(blockingDeque, taskAmount);
new Thread(producer).start();
Consumer consumer = new Consumer(blockingDeque);
new Thread(consumer).start();
}
}
7. ProducerConsumerApplication
SpringBoot应用启动类
package com.elon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProducerConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerConsumerApplication.class);
System.out.println("Startup ProducerConsumerApplication success.");
}
}
三、通过swagger接口测试
从打印的信息来看。消费者线程在收到标识所有任务已完成的毒丸后就结束消费。这是已知生产者需要生产多少任务的情况,如果生产任务数量不确定,则需要根据外部输入的数据实时生成任务。
源码地址:https://github.com/ylforever/elon-producerconsumer