Often handwritten code

1. Thread deadlock case

public class DeadLock {
    public static void main(String[] args) {
        Person person1 = new Person(0."Zhang");
        Person person2 = new Person(1."Bill"); person1.start(); person2.start(); }}/** ** spoon */
class Spoon{}/** ** fork */
class Fork{}/ * * * * /
class Person extends Thread{
    static Spoon spoon = new Spoon();
    static Fork fork = new Fork();
​
    int choice;
    String personName;
​
    public Person(int choice,String personName){
        this.choice = choice;
        this.personName = personName;
    }
​
    @Override
    public void run(a) {
        try {
            eat();
        } catch(InterruptedException e) { e.printStackTrace(); }}public void eat(a) throws InterruptedException {
        if (choice == 0) {synchronized (spoon){
                System.out.println(this.personName + "Got the spoon.");
                Thread.sleep(1000);
                synchronized (fork){
                    System.out.println(this.personName + "Got a fork."); }}}else{
            synchronized (fork){
                System.out.println(this.personName + "Got a fork.");
                Thread.sleep(1000);
                synchronized (spoon){
                    System.out.println(this.personName + "Got the spoon.");
                }
            }
        }
    }
}
Copy the code

Examples of static proxies

/** * static proxy: marriage case */
public class StaticProxy {
    public static void main(String[] args) {
        WeddingCompany weddingCompany = new WeddingCompany(newYou()); weddingCompany.happyMarry(); }}/ / to get married
interface Marry {
    void happyMarry(a);
}

// True character: You get married
class You implements Marry {
    @Override
    public void happyMarry(a) {
        System.out.println("Doris is so happy to get married."); }}// Proxy role: help you get married
class WeddingCompany implements Marry {
    private Marry target;// Agent --> Real target character character, help who get married

    public WeddingCompany(Marry target) {
        this.target = target;
    }

    @Override
    public void happyMarry(a) {
        after();
        this.target.happyMarry();
        before();
    }

    private void after(a) {
        System.out.println("Before you get married, set the scene.");
    }

    private void before(a) {
        System.out.println("After the wedding, the closing money."); }}Copy the code

3. Simple mode for RabbitMQ

  • producers
public class Producer {
    // Define a queue name
    public static final String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168. XXX. XXX");
        factory.setUsername("XXXX");
        factory.setPassword("XXXX");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false.false.false.null);
        String message = "hello world";
        channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
        System.out.println("Message sent complete"); }}Copy the code
  • consumers
public class Consumer {
    public static final String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168. XXX. XXX");
        factory.setUsername("XXXX");
        factory.setPassword("XXXX");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        System.out.println("Waiting to receive a message...");
        DeliverCallback deliverCallback = (consumerTag,message)->{
            String mes = new String(message.getBody());
            System.out.println("The message received is" + mes);
        };
        CancelCallback cancelCallback = (String consumerTag)->{
            System.out.println("Message cut off...");
        };
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback); }}Copy the code

4. Work Queue for RabbitMQ

  • Utility class
public class RabbitMqUtil{
    public static Channel getChannel(a) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.200.130");
        factory.setUsername("admin");
        factory.setPassword("123");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        returnchannel; }}Copy the code
  • producers
public class Task01 {
    private static final String QUEUE_NAME = "work";

    public static void main(String[] args) throws Exception {
        try (Channel channel = RabbitMqUtil.getChannel();) {
            channel.queueDeclare(QUEUE_NAME, false.false.false.null);
// Receive information from the console
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String message = scanner.next();
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
                System.out.println("Sending message completed :"+ message); }}}}Copy the code
  • consumers
public class Worker01 {
    public static final String QUEUE_NAME = "work";

    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMqUtil.getChannel();
        DeliverCallback deliverCallback = (consumerTag,message)->{
            String mes = new String(message.getBody());
            System.out.println("The message received is" + mes);
            System.out.println("Output complete");
        };
        CancelCallback cancelCallback = (consumerTag)->{
            System.out.println("Output error");
        };
        System.out.println("C2 waiting to receive message");
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,cancelCallback); }}Copy the code

5. RabbitMQ message reply

Normally RabbitMQ sends a message to the consumer and deletes it, but if the consumer hangs up, the message is lost.

RabbitMQ then introduces a message reply mechanism, which does not delete the RabbitMQ message after it is sent to the consumer, but waits for the consumer to receive and process the message and then reply to RabbitMQ to say that the message can be deleted so that the message is not lost.

Generally, manual answer is used.

  • Consumer 1
public class Worker03 {
    public static final String TASK_QUEUE_NAME = "ack_queue";
    // Receive the message
    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMqUtil.getChannel();
        System.out.println("C1 is waiting for receiving message processing, and the time is relatively short");
        DeliverCallback deliverCallback = (consumerTag,message)->{
            SleepUtils.sleep(1);
            System.out.println("The message received is" + new String(message.getBody(),"UTF-8"));
            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
        };

        // Use manual reply
        boolean autoAck = false; channel.basicConsume(TASK_QUEUE_NAME,autoAck,deliverCallback,(consumerTag -> {})); }}Copy the code
  • Consumer 2
public class Worker04 {
    public static final String TASK_QUEUE_NAME = "ack_queue";
    // Receive the message
    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMqUtil.getChannel();
        System.out.println("C2 waits for receiving message processing for a short time");
        DeliverCallback deliverCallback = (consumerTag,message)->{
            SleepUtils.sleep(30);
            System.out.println("The message received is" + new String(message.getBody(),"UTF-8"));
            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
        };

        // Use manual reply
        boolean autoAck = false; channel.basicConsume(TASK_QUEUE_NAME,autoAck,deliverCallback,(consumerTag -> {})); }}Copy the code
  • producers
public class Task02 {
    // New queue name
    public static final String TASK_QUEUE_NAME = "ack_queue";

    // Send a message
    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMqUtil.getChannel();
        channel.queueDeclare(TASK_QUEUE_NAME,false.false.false.null);
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String message = scanner.next();
            channel.basicPublish("",TASK_QUEUE_NAME,null,message.getBytes("UTF-8"));
            System.out.println("Producer sends message :"+ message); }}}Copy the code

6. Unfair reception of RabbitMQ

  • Producer: Same code as in the previous case
  • Consumer: Just add two lines to the code
int prefetchCount = 1;
channel.basicQos(prefetchCount);
Copy the code

Actual code :(two similar, write only one)

public class Worker04 {
    public static final String TASK_QUEUE_NAME = "ack_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMqUtil.getChannel();
        System.out.println("C4 waiting for receiving message processing time is long");
        DeliverCallback deliverCallback = (consumerTag,message)->{
            String mes = new String(message.getBody(),"UTF-8");
            SleepUtils.sleep(15);
            System.out.println("Message received" + mes);
            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
        };
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);
        boolean autoAck = false; channel.basicConsume(TASK_QUEUE_NAME,autoAck,deliverCallback,(consumerTag -> {})); }}Copy the code