RabbitMQ : Spring AMQP 큐 메시지 송신, 수신

Programming/Java 2021. 5. 29. 15:51 Posted by 파란크리스마스

출처

pom.xml

		<dependency>
			<groupId>org.springframework.amqp</groupId>
			<artifactId>spring-amqp</artifactId>
			<version>2.1.12.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.amqp</groupId>
			<artifactId>spring-rabbit</artifactId>
			<version>2.1.12.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.12.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.12.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.12.3</version>
		</dependency>

		<!-- RabbitMQ Client -->
		<dependency>
			<groupId>com.rabbitmq</groupId>
			<artifactId>amqp-client</artifactId>
			<version>5.8.0</version>
		</dependency>

Spring AMQP 큐 메시지 송신

bluexmas-mq-rabbitmq.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:rabbit="http://www.springframework.org/schema/rabbit"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/rabbit    https://www.springframework.org/schema/rabbit/spring-rabbit.xsd
	                    http://www.springframework.org/schema/beans     https://www.springframework.org/schema/beans/spring-beans.xsd
	                    http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<!-- RabbitMQ 연결 설정 -->
	<rabbit:connection-factory id="rabbitConnectionFactory" 
		virtual-host="/" 
		host="lastxmas.iptime.org" 
		port="5672"
		channel-cache-size="10" 
		username="admin" 
		password="passwd"/>
		
	<rabbit:admin connection-factory="rabbitConnectionFactory"/>
	
	<!-- Queue 등록 -->
	<rabbit:queue auto-declare="true" name="myQueue" />
	
	<rabbit:direct-exchange name="amq.direct">
		<rabbit:bindings>
			<rabbit:binding key="foo.bar" queue="myQueue"/>
		</rabbit:bindings>
	</rabbit:direct-exchange>
	
	<!-- 생산자와 소비자 모두에게 필요한 메시지 변환 -->
	<bean id="amqpMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"/>

	<!-- 메시지 리스너 설정 -->
	<rabbit:listener-container connection-factory="rabbitConnectionFactory" message-converter="amqpMessageConverter">
		<!-- 큐 myQueue 메시지는 bean id consumer의 method handleMessage가 처리한다 -->
		<rabbit:listener queues="myQueue" ref="MQConsumer" method="handleMessage"/>
	</rabbit:listener-container>
	
	<bean id="MQConsumer" class="com.bluexmas.mq.MQConsumer"/>
	
</beans>

메시지 수신 클래스 ( MQConsumer.java )

package com.bluexmas.mq;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import com.bluexmas.dao.domain.CustomMessage;
import com.bluexmas.dao.domain.MPSMessage;

@Component
public class MQConsumer {
	
	//메시지를 처리한다.
	public void handleMessage(Message message) {
		//do Something
		System.out.println(message);		
	}
	
	//메시지를 처리한다.
	public void handleMessage(CustomMessage message) {
		//do Something
		System.out.println("--1> " +  message);
	}
	
}

Spring AMQP 큐 수동으로 전달

메시지 큐 전달 객체 ( CustomMessage.java )

package com.bluexmas.dao.domain;

public class CustomMessage {
	
	private String text;

	private int priority;

	private boolean secret;

	protected CustomMessage() {
	}

	public CustomMessage(String text, int priority, boolean secret) {
		this.text = text;
		this.priority = priority;
		this.secret = secret;
	}

	public String getText() {
		return text;
	}

	public int getPriority() {
		return priority;
	}

	public boolean isSecret() {
		return secret;
	}

	@Override
	public String toString() {
		return "CustomMessage{" + "text='" + text + '\'' + ", priority=" + priority + ", secret=" + secret + '}';
	}

}

메시지 전달 객체 ( ProducerJSon2.java )

package com.bluexmas.test;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;

import com.bluexmas.dao.domain.CustomMessage;
import com.fasterxml.jackson.core.JsonProcessingException;

public class ProducerJSon2 {
	public static void main(final String[] args) throws JsonProcessingException {
		// RabbitMQ 연결
		CachingConnectionFactory cf = new CachingConnectionFactory("lastxmas.iptime.org", 5672);
		cf.setUsername("admin");
		cf.setPassword("passwd");

		// 메시지 보내기
		RabbitTemplate template = new RabbitTemplate(cf);
		template.setExchange("amq.direct");
		template.setQueue("myQueue");
		template.setMessageConverter(new Jackson2JsonMessageConverter());
		
		CustomMessage customMessage = new CustomMessage("Hello Message!", 1, true);
		template.convertAndSend("foo.bar", customMessage);
		cf.destroy();
	}
}

로그

00:29:34.276 [pool-1-thread-4] DEBUG org.springframework.amqp.rabbit.listener.BlockingQueueConsumer - Storing delivery for consumerTag: 'amq.ctag-5t1nRdDJwg8A-H8jTH6DqQ' with deliveryTag: '1' in Consumer@1e292e89: tags=[[amq.ctag-5t1nRdDJwg8A-H8jTH6DqQ]], channel=Cached Rabbit Channel: AMQChannel(amqp://admin@1.229.109.140:5672/,1), conn: Proxy@eefafec Shared Rabbit Connection: SimpleConnection@3680d2bb [delegate=amqp://admin@1.229.109.140:5672/, localPort= 4263], acknowledgeMode=AUTO local queue size=0

00:29:34.293 [org.springframework.amqp.rabbit.config.ListenerContainerFactoryBean#0-1] DEBUG org.springframework.amqp.rabbit.listener.BlockingQueueConsumer - Received message: (Body:'{"text":"Hello Message!","priority":1,"secret":true}' MessageProperties [headers={__TypeId__=com.bluexmas.dao.domain.CustomMessage}, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=amq.direct, receivedRoutingKey=foo.bar, deliveryTag=1, consumerTag=amq.ctag-5t1nRdDJwg8A-H8jTH6DqQ, consumerQueue=myQueue])

--1> CustomMessage{text='Hello Message!', priority=1, secret=true}

댓글을 달아 주세요

RabbitMQ : 계정 및 가상호스트(Virtual Host) 추가

Programming/Java 2021. 5. 29. 11:29 Posted by 파란크리스마스

출처

사용자추가

Admin 탭으로 이동

사용자 정보를 입력하고 [Add user] 버튼 선택

가상호스트 추가

가상호스트를 추가할 사용자 선택

[Virtual Host] 선택하고 [Set permission] 버튼 선택

확인

댓글을 달아 주세요

Amazon Linux(centos) : MySQL 5.7.23 컴파일, 설치

Database 2021. 5. 7. 09:39 Posted by 파란크리스마스

출처

리눅스 정보 조회

출처 : 리눅스 종류 확인, 리눅스 버전 확인 - 제타위키

$ cat /etc/*-release
NAME="Amazon Linux"
VERSION="2"
ID="amzn"
ID_LIKE="centos rhel fedora"
VERSION_ID="2"
PRETTY_NAME="Amazon Linux 2"
ANSI_COLOR="0;33"
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
HOME_URL="https://amazonlinux.com/"
Amazon Linux release 2 (Karoo)

관련패키지 설치

$ sudo yum update
$ sudo yum install gcc gcc-c++ openssl curl autoconf ncurses-devel bison zlib curl libtermcap-devel bzip2-devel

MySQL 계정 만들기

$ sudo groupadd mysql 
$ sudo useradd -g mysql -s /bin/bash -m mysql

cmake 설치

$ sudo yum install cmake

MySQL 소스 다운로드, 압축해제, 컴파일, 설치

$ wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-boost-5.7.23.tar.gz 
$ tar xvf mysql-boost-5.7.23.tar.gz 
$ cd mysql-5.7.23 
$ cmake \ 
  -DCMAKE_INSTALL_PREFIX=/usr/local/mysql57 \ 
  -DMYSQL_DATADIR=/usr/local/mysql57/data \ 
  -DMYSQL_UNIX_ADDR=/usr/local/mysql57/mysql.sock \ 
  -DSYSCONFDIR=/usr/local/mysql57 \ 
  -DMYSQL_TCP_PORT=5723 \ 
  -DMYSQL_USER=mysql \ 
  -DDEFAULT_CHARSET=utf8 \ 
  -DDEFAULT_COLLATION=utf8_general_ci \ 
  -DWITH_EXTRA_CHARSETS=all \ 
  -DENABLED_LOCAL_INFILE=1 \ 
  -DWITH_INNOBASE_STORAGE_ENGINE=1 \ 
  -DWITH_ARCHIVE_STORAGE_ENGINE=1 \ 
  -DWITH_BLACKHOLE_STORAGE_ENGINE=1 \ 
  -DDOWNLOAD_BOOST=0 \
  -DWITH_BOOST=./boost 
$ make 
$ sudo make install

환경설정

$ sudo vi /usr/local/mysql57/my.cnf

[mysqld]
# port=3306
# basedir=/usr/local/mysql57
# datadir=/usr/local/mysql57/data
# pid-file=/usr/local/mysql57/mysqld.pid
# log_error=/usr/local/mysql57/mysql_error.log
# lc-messages-dir=/usr/local/mysql57/share

init_connect=SET collation_connection = utf8_general_ci
init_connect=SET NAMES utf8
character-set-server=utf8
collation-server=utf8_general_ci
# table_cache=1024
max_connections=2048
max_user_connections=500
max_connect_errors=10000
wait_timeout=300
query_cache_type = 1
query_cache_size = 128M
query_cache_limit = 5M
slow_query_log
long_query_time=3
max_allowed_packet=16M
sort_buffer_size = 2M
# skip-innodb
skip-name-resolve
sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

[mysql]
default-character-set=utf8

[client]
default-character-set=utf8

MySQL 설치 디렉토리 mysql 계정으로 권한 수정

$ sudo chown -R mysql:mysql /usr/local/mysql57

MySQL 데이터베이스 초기화 (mysql 계정으로 실행)

$ cd /usr/local/mysql57
$ bin/mysql_install_db --no-defaults --user=mysql --datadir=/usr/local/mysql57/data --basedir=/usr/local/mysql57 -v
2021-05-08 08:15:24 [WARNING] mysql_install_db is deprecated. Please consider switching to mysqld --initialize
2021-05-08 08:15:24 [NOTE]    Creating data directory /usr/local/mysql57/data
2021-05-08 08:15:24 [NOTE]    Generating random password to /root/.mysql_secret...done.
2021-05-08 08:15:24 [NOTE]    Setting file ownership to mysql
2021-05-08 08:15:24 [NOTE]    Executing /usr/local/mysql57/bin/mysqld --no-defaults --bootstrap --datadir=/usr/local/mysql57/data --lc-messages-dir=/usr/local/mysql57/share --lc-messages=en_US --basedir=/usr/local/mysql57
2021-05-08 08:15:24 [NOTE]    Creating system tables...done.
2021-05-08 08:15:24 [NOTE]    Filling system tables with data...done.
2021-05-08 08:15:25 [NOTE]    Filling help table with data...done.
2021-05-08 08:15:25 [NOTE]    Creating user for internal session service...done.
2021-05-08 08:15:25 [NOTE]    Creating default user root@localhost
2021-05-08 08:15:25 [NOTE]    Creating default proxy root@localhost
2021-05-08 08:15:25 [NOTE]    Creating sys schema
2021-05-08 08:15:25 [NOTE]    done.
2021-05-08 08:15:26 [WARNING] The bootstrap log isn't empty:
2021-05-08 08:15:26 [WARNING] 2021-05-08T08:15:24.294574Z 0 [Warning] --bootstrap is deprecated. Please consider using --initialize instead
2021-05-08T08:15:24.299965Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 5000)
2021-05-08T08:15:24.299974Z 0 [Warning] Changed limits: table_open_cache: 431 (requested 2000)
 
2021-05-08 08:15:26 [NOTE]    Generating SSL Certificates

MySQL 서비스 등록

서비스 mysqld 파일 복사

$ sudo cp /usr/local/mysql57/support-files/mysql.server /etc/init.d/mysqld57

mysqld 수정

$ sudo vi /etc/init.d/mysqld57

mysqld파일을 열어서 basedir에 mysql이 설치된 디렉토리와 데이터 디렉토리(datadir)를 설정한다.

basedir=/usr/local/mysql57
datadir=/usr/local/mysql57/data

mysqld 서비스 등록

$ sudo chkconfig --add mysqld57
$ sudo chmod +x /etc/init.d/mysqld57
$ chkconfig --list
 
Note: This output shows SysV services only and does not include native
      systemd services. SysV configuration data might be overridden by native
      systemd configuration.

      If you want to list systemd services use 'systemctl list-unit-files'.
      To see services enabled on particular target use
      'systemctl list-dependencies [target]'.
 
mysqld57        0:off   1:off   2:on    3:on    4:on    5:on    6:off
netconsole      0:off   1:off   2:off   3:off   4:off   5:off   6:off
network         0:off   1:off   2:on    3:on    4:on    5:on    6:off
tomcat          0:off   1:off   2:off   3:on    4:on    5:on    6:off
$ sudo chkconfig --level 345 mysqld57 on

mysqld 서비스 실행

$ sudo service mysqld57 start
Starting MySQL. SUCCESS!

root 암호 초기화

mysqld 실행

$ sudo bin/mysqld_safe --skip-grant-tables &
[1] 11505
2021-05-08T08:56:04.765371Z mysqld_safe Logging to '/var/log/mysqld.log'.
2021-05-08T08:56:04.792894Z mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql

root 암호 설정

$ bin/mysql -u root -p 
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.23-log Source distribution
 
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
 
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
 
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
 
mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
 
Database changed
mysql> update user set authentication_string = password('manager') where user = 'root';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1
 
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
 
mysql> quit
Bye

ERROR 1820 (HY000) 오류 해결

mysql> use mysql
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
mysql> SET PASSWORD = PASSWORD('soY&Be9p/4ed!!!'); 
Query OK, 0 rows affected, 1 warning (0.00 sec)
 
mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
 
Database changed
mysql> 

사용자 추가

mysql> create user 'user1'@'%' identified by 'userpw';
Query OK, 0 rows affected (0.00 sec)
 
mysql> grant all privileges on *.* to 'user1'@'%' with grant option; 
Query OK, 0 rows affected (0.00 sec)
 
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

사용자 추가 - 특정 DB에 권한 부여

mysql> create user 'terecal'@'%' identified by '****'; 
Query OK, 0 rows affected (0.00 sec)
 
mysql> grant all privileges ON terecal_db.* TO 'terecal'@'%'; 
Query OK, 0 rows affected (0.00 sec)
 
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

댓글을 달아 주세요

Ender 5 : SKR mini e3 v2.0 bltouch

3D 프린터 2021. 5. 3. 22:54 Posted by 파란크리스마스

출처

 

SKR mini E3 v2.0에 권장되는 BLTouch 배선

BLTouch 설치

Configuration.h

BLTouch 활성화

/**
 * The BLTouch probe uses a Hall effect sensor and emulates a servo.
 */
#define BLTOUCH

노즐과 BLTouch 사이 간격 설정

/**
 * Z Probe to nozzle (X,Y) offset, relative to (0, 0).
 *
 * In the following example the X and Y offsets are both positive:
 *
 *   #define NOZZLE_TO_PROBE_OFFSET { 10, 10, 0 }
 *
 *     +-- BACK ---+
 *     |           |
 *   L |    (+) P  | R <-- probe (20,20)
 *   E |           | I
 *   F | (-) N (+) | G <-- nozzle (10,10)
 *   T |           | H
 *     |    (-)    | T
 *     |           |
 *     O-- FRONT --+
 *   (0,0)
 *
 * Specify a Probe position as { X, Y, Z }
 */
#define NOZZLE_TO_PROBE_OFFSET { 0, -38, 0 }

Z_SAFE_HOMING 활성화

Home 이동시 베드 외부로 이동 하는 것을 방지하기 위해서 Z_SAFE_HOMING을 활성화 시켜 주므로 베드의 가운데로 이동하도록 하기 위함(NOZZLE_TO_PROBE_OFFSET 값이 올바르지 않는 경우 베드의 외부로 이동 할수 있음)

// Use "Z Safe Homing" to avoid homing with a Z probe outside the bed area.
//
// With this feature enabled:
//
// - Allow Z homing only after X and Y homing AND stepper drivers still enabled.
// - If stepper drivers time out, it will need X and Y homing again before Z homing.
// - Move the Z probe (or nozzle) to a defined XY point before Z Homing.
// - Prevent Z homing when the Z probe is outside bed area.
//
#define Z_SAFE_HOMING

#if ENABLED(Z_SAFE_HOMING)
  #define Z_SAFE_HOMING_X_POINT X_CENTER  // X point for Z homing
  #define Z_SAFE_HOMING_Y_POINT Y_CENTER  // Y point for Z homing
#endif

AUTO_BED_LEVELING_BILINEAR 활성화

Z축 엔드스탑 스위치에 의해서 멈추던 것을 BLTouch의 신호에 의해서 멈추도록 설정

// Mechanical endstop with COM to ground and NC to Signal uses "false" here (most common setup).
#define X_MIN_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Y_MIN_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Z_MIN_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define X_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Y_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
#define Z_MAX_ENDSTOP_INVERTING false // Set to true to invert the logic of the endstop.
//#define Z_MIN_PROBE_ENDSTOP_INVERTING false // Set to true to invert the logic of the probe.
#define Z_MIN_PROBE_ENDSTOP_INVERTING true // Set to true to invert the logic of the probe.

Z_MIN_PROBE_ENDSTOP_INVERTING 활성화, MESH_BED_LEVELING 비활성화

MESH_BED_LEVELING : 수동으로 레벨링 측정하는 옵션은 비활성화 시키고,
AUTO_BED_LEVELING_BILINEAR : 그리드 형태로 여러지점을 샘플지점으로 베드 레벨링을 측정하도록 설정 (높이가 고르지 않은 배드에 가장 적합)

/**
 * Choose one of the options below to enable G29 Bed Leveling. The parameters
 * and behavior of G29 will change depending on your selection.
 *
 *  If using a Probe for Z Homing, enable Z_SAFE_HOMING also!
 *
 * - AUTO_BED_LEVELING_BILINEAR
 *   Probe several points in a grid.
 *   You specify the rectangle and the density of sample points.
 *   The result is a mesh, best for large or uneven beds.
 *
 * - MESH_BED_LEVELING
 *   Probe a grid manually
 *   The result is a mesh, suitable for large or uneven beds. (See BILINEAR.)
 *   For machines without a probe, Mesh Bed Leveling provides a method to perform
 *   leveling in steps so you can manually adjust the Z height at each grid-point.
 *   With an LCD controller the process is guided step-by-step.
 */
//#define AUTO_BED_LEVELING_LINEAR
#define AUTO_BED_LEVELING_BILINEAR // <-- 주석 제거
//#define AUTO_BED_LEVELING_UBL
//#define MESH_BED_LEVELING // <- 주석 추가

GRID_MAX_POINTS_X 값 변경

그리드 형태로 샘플지점을 5x5에서 3x3으로 변경 (너무 촘촘하게 측정은 불필요 하다고 판단)

  // Set the number of grid points per dimension.
  #define GRID_MAX_POINTS_X 3 // 5 -> 3
  #define GRID_MAX_POINTS_Y GRID_MAX_POINTS_X

MIN_SOFTWARE_ENDSTOP_Z 주석 추가

Z move 마이너스값 허용

// Min software endstops constrain movement within minimum coordinate bounds
#define MIN_SOFTWARE_ENDSTOPS
#if ENABLED(MIN_SOFTWARE_ENDSTOPS)
  #define MIN_SOFTWARE_ENDSTOP_X
  #define MIN_SOFTWARE_ENDSTOP_Y
  // #define MIN_SOFTWARE_ENDSTOP_Z  // 주석시 - Z move 마이너스값 허용
#endif

Configuration_adv.h

BLTOUCH_DELAY 주석 제거

BLTouch가 측정한 값을 인식하는 데 필요한 지연 시간 설정(시간 단위(ms). 필요한 경우 활성화하고 지연 시간을 늘려서 설정도 가능)

  // Safety: The probe needs time to recognize the command.
  //         Minimum command delay (ms). Enable and increase if needed.
  #define BLTOUCH_DELAY 500  // <- 주석제거

BLTOUCH_FORCE_SW_MODE 주석 제거

  // Feature: Switch into SW mode after a deploy. It makes the output pulse longer. Can be useful
  //          in special cases, like noisy or filtered input configurations.
  #define BLTOUCH_FORCE_SW_MODE  // <- 주석제거

컴파일

CURA GCode 추가

;When using Default mode, you do not need to declare logic mode. 
M280 P0 S160 ; BLTouch alarm release 
G4 P100 ; delay for BLTouch 
G28 ; home 
G29 ; auto bed leveling

 

댓글을 달아 주세요