RabbitMQ를 사용하여 다음 주차장 시뮬레이션을 비동기식으로 만들려면 어떻게 해야 합니까?

9480 단어 rabbitmqamqpjavamqp
0

Java의 동시성에 대한 다양한 접근 방식을 배우고 이해하려고 합니다. 저는 주차장 시뮬레이션의 직렬화된 구현을 가지고 있습니다. 프로그램이 대신 Rabbitmq를 사용하도록 만들고 싶습니다. 어떻게 해야 합니까?

아래는 구현 측면에서도 개선될 수 있는 주차장 클래스입니다.

편집: 내 주요 질문은 실제로 루프에서 Pub/sub를 어떻게 수행할 수 있는지 깨달았습니다.2. pub/sub도 필요합니까?

`
공공 클래스 주차 {

public static void main(String[] args) throws InterruptedException {

    Parking parkingObj = new Parking();

    parkingObj.runSimulation();

}

public void runSimulation() throws InterruptedException{
    int numOfRuns = 101;//100 runs
    int currentRuns = 1;

    securityGuard myGuard = new securityGuard();

    //spot mySpot = new spot();

    ArrayList<ticketClass> ticketArray = new ArrayList<>();

    int bouncedCustomers = 1;
    spot availableSpot = new spot();


    //Random randomExit  = new Random();

    while (currentRuns < numOfRuns){
        Random randomSleep  = new Random();

        //Car object instantiation  
        carClass vehicle = new carClass();
        //ticketClass ticketObj = new ticketClass();

        //Random time generator 

        Random randomTime = new Random();


        //instantiation of the info geneatator class

        infoGenerator info = new infoGenerator();


        //Generaring random Car info 

        String plateNumber = info.plateGenerator();
        String carModel = info.modelGenerator();
        String color = info.colorGenerator();

        if (availableSpot.getSpotNum() == 15 ){
                   System.out.println("Carpark full, No cars allowed unitl a space is free");

                   //Customers waiting for free space
                   Thread.sleep(9000);

                   System.out.println("Total Waiting customers: " + bouncedCustomers);

                   bouncedCustomers += 1;

        }
        else{

            //System.out.println("Customer Exiting");
            Thread.sleep(randomTime.nextInt(5000));

            meterClass myMeter = new meterClass();

            ticketClass myTicket = myGuard.ticketGenerator(vehicle, myMeter);
            //ticketClass myTicket = new ticketClass();
            myTicket.setmeter(myMeter);
            myTicket.setCar(vehicle);
            myTicket.getCar().plateSetter(plateNumber);
            myTicket.getCar().colorSetter(color);
            myTicket.getCar().modelSeter(carModel);
            myTicket.getCar().minSetter(randomTime.nextInt(100));

            //Details are only set if there is space available
            //The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
            myMeter.setPurchasedMinutes(randomTime.nextInt(72));


            System.out.println("\n\nCar " + currentRuns + " has entered the car park");
            System.out.println("\nCAR DETAILS:");
            System.out.println(carModel);
            System.out.println(plateNumber);
            System.out.println(color);


            int spotAvail = availableSpot.assignSpot();

            myTicket.setSlotNum(spotAvail);


            //Set the time the car entered 
            String timeIn = info.timeMonitor();

            //myTicket.


            ticketArray.add(myTicket);
            System.out.println("\n\n===Total customers: " + ticketArray.size());


            System.out.println(timeIn+"\n");

            availableSpot.spotLog();


        }
        //Cars leaving at random times

        for (int i= 0; i < ticketArray.size();i++ ){

                meterClass meterOut =  ticketArray.get(i).getMeter();
                carClass ExitCar = ticketArray.get(i).getCar();


                if(myGuard.checkParking(ExitCar,meterOut)){
                    System.out.println("\nCustomer " + ExitCar.plateGetter()+ " is exiting the carpark...");
                    double penaltyVal = ticketArray.get(i).getPenalty();
                    System.out.println("FINE: " + penaltyVal);
                    System.out.println("==================================================================");
                    Thread.sleep(randomTime.nextInt(4000));
                    ticketArray.remove(ticketArray.remove(i));
                    availableSpot.spotFree(i);

                }




        }




    currentRuns += 1;

    }





}

}
`
TLDR: 다음 코드를 구조적으로나 속도 측면에서 최적화해야 합니다(특히 RabbitMQ와 함께 멀티스레딩 사용).

현재 상태로는 무한루프를 돌고 있으며 벌금값은 0이다.

공개 클래스 securityGuard{

    public String badgeNumber;
    public String guardName;

    securityGuard(){}

    securityGuard(String badgeNumber, String guardName){

        this.badgeNumber = badgeNumber;
        this.guardName = guardName;           
    }

    public void setBadgeNumber(String badgeNumber){
        this.badgeNumber = badgeNumber;
    }

    public String getBadgeNumber(){

        return badgeNumber;

    }

    public void setguardName(String guardName){
        this.guardName = guardName;
    }

    public String getGuardName(){

        return guardName;

    }

    public boolean checkParking(carClass car,meterClass meter){

        return car.minGetter() > meter.getPurchasedMinutes();
    }  

    public ticketClass ticketGenerator(carClass car, meterClass meterVar){

        ticketClass myTicket = new ticketClass(car,this);

        int timeRemaining = car.minGetter() - meterVar.getPurchasedMinutes();

        if(checkParking(car,meterVar)){
            if (timeRemaining < 60){
                myTicket.penalty = 50;
            }

            else {
                myTicket.penalty = 50 + (10 * (timeRemaining/60));
            }





    }
return myTicket;


}

}

다른 수업과 관련하여 추가 정보가 필요하거나 누락된 내용이 있으면 알려주세요. 미리 감사드립니다.

편집하다:

아래는 생산자 구현에 대한 나의 시도입니다. 100개의 무작위 메시지 게시를 목표로 run 메서드에서 for 루프를 사용해 보았습니다.

public class entrySimulation은 Runnable을 구현합니다.

int numOfRuns = 100;//1000 runs
int currentRuns = 1;

securityGuard_exp_1 myGuard = new securityGuard_exp_1();


//System.out.println("Customer Exiting");

//Thread.sleep(randomTime.nextInt(5000));

meterClass_exp_1 myMeter = new meterClass_exp_1();
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min


//instantiation of the info generator class

infoGenerator_exp_1 info = new infoGenerator_exp_1();

//Generating random Car info


//spot_exp_1 mySpot = new spot_exp_1();
//Use an iterator
 List<ticketClass_exp_1> ticketArray = new ArrayList<>();

Iterator<ticketClass_exp_1> iter = ticketArray.iterator();

public final spot_exp_1 availableSpot = new spot_exp_1();

//Random time generator
Random randomTime = new Random();


public static void main(String[] args) {

    String exchangeName = "entryExchange";
    String routingKey = "exitKey";
    String message = "";

    //Creating a connection factory

    ConnectionFactory factory = new ConnectionFactory();

    //Creating new connection

    try(Connection conVar = factory.newConnection();){

        Channel channelCon = conVar.createChannel();

        //Exchange declaration

        channelCon.exchangeDeclare(exchangeName,"customerExit");



        channelCon.basicPublish(exchangeName,routingKey,null,message.getBytes(StandardCharsets.UTF_8));

        System.out.println("Customer Exited");





    }catch(Exception e){}


}




@Override
public void run() {

    for (int i = 0; i < numOfRuns; i++) {
        //System.out.println(i);


        String plateNumber = info.plateGenerator();
        String carModel = info.modelGenerator();
        String color = info.colorGenerator();

        myMeter.setPurchasedMinutes(randomTime.nextInt(30));


        carClass_exp1_1 vehicle = new carClass_exp1_1(carModel, color, plateNumber, randomTime.nextInt(2880));
        ticketClass_exp_1 myTicket = myGuard.ticketGenerator(vehicle, myMeter);



        //Generating details
        myTicket.setmeter(myMeter);
        myTicket.setCar(vehicle);
        myTicket.getCar().plateSetter(plateNumber);
        myTicket.getCar().colorSetter(color);
        myTicket.getCar().modelSeter(carModel);
        myTicket.getGuard().setguardName("Phill");
        myTicket.getGuard().setBadgeNumber("AF170");
        int spotAvail = availableSpot.assignSpot();
        myTicket.setSlotNum(spotAvail);


        //Set the time the car entered
        String timeIn = info.timeMonitor();


        //message
        System.out.println("\n\nCar " + currentRuns + " has entered the car park");
        System.out.println("\nCAR DETAILS:");
        System.out.println(carModel);
        System.out.println(plateNumber);
        System.out.println(color);
        System.out.println("Penalty" + myTicket.getPenalty());
        ticketArray.add(myTicket);
        System.out.println("============================================|");
        System.out.println("TIME IN: " + timeIn);
        //System.out.println("\n\n===Total customers: " + myTicket.slotNum);



        //message
        availableSpot.spotLog();





    }


}

}

그러나 방법을 모르겠습니다. 누구든지 어떤 식으로든 도울 수 있다면 제발. 죄송합니다, 이것은 저에게 매우 새로운 개념입니다

좋은 웹페이지 즐겨찾기