728x90

CIFS 유틸리티 설치

bluesanta@bluesanta-desktop:~$ sudo apt update
bluesanta@bluesanta-desktop:~$ sudo apt install cifs-utils

CIFS 유틸리티 설치

bluesanta@bluesanta-desktop:~$ sudo apt update
bluesanta@bluesanta-desktop:~$ sudo apt install cifs-utils

일회성 수동 마운트

마운트 포인트 생성

bluesanta@bluesanta-desktop:~$ sudo mkdir -p /mnt/samba

마운트 실행

bluesanta@bluesanta-desktop:~$ sudo mount -t cifs //192.168.0.223/samba_root /mnt/samba -o username=bluesanta,password=비밀번호,iocharset=utf8

-

 

728x90
728x90

OpenJDK 17 설치

bluesanta@bluesanta-AI-Series:~/Application/Android$ sudo apt install openjdk-17-jdk

JAVA_HOME 설정

JDK 설치 경로 확인

bluesanta@bluesanta-AI-Series:~/Application/Android$ readlink -f $(which java)
/usr/lib/jvm/java-17-openjdk-amd64/bin/java

환경 변수 파일 수정

bluesanta@bluesanta-AI-Series:~/Application/Android$ vi ~/.bashrc

파일 맨 아래에 다음 내용 추가

export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
export PATH=$PATH:$JAVA_HOME/bin

32비트 라이브러리 설치

Ubuntu 64비트 환경에서 Android SDK의 일부 도구(특히 에뮬레이터나 오래된 빌드 도구)를 실행하려면 32비트 호환 라이브러리가 필요할 수 있으므로 미리 설치

i386 아키텍처 활성화

bluesanta@bluesanta-AI-Series:~/Application/Android$ sudo dpkg --add-architecture i386

32비트 라이브러리 설치

bluesanta@bluesanta-AI-Series:~/Application/Android$ sudo apt update
bluesanta@bluesanta-AI-Series:~/Application/Android$ sudo apt-get install libc6:i386 libncurses6:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386

라이선스 동의 및 필수 패키지 설치

라이선스 동의

bluesanta@bluesanta-AI-Series:~/Application/Android/sdk-tools-windows.old/cmdline-tools/latest/bin$ ./sdkmanager --licenses

3필수 패키지 설치

bluesanta@bluesanta-AI-Series:~/Application/Android/sdk-tools-windows.old/cmdline-tools/latest/bin$ ./sdkmanager "platform-tools" "platforms;android-35" "build-tools;35.0.0" --sdk_root=/home/bluesanta/Application/Android/sdk-tools-windows
728x90
728x90

출처

PyTorch 소스 가져오기

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama$ sudo apt install -y python3-pip cmake git ninja-build
(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama$ pip install --upgrade setuptools wheel
(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama$ git clone --recursive https://github.com/pytorch/pytorch
(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama$ cd pytorch
(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ git checkout v2.10.0
(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ git submodule update --init --recursive

HX 390(gfx1150) 전용 빌드 환경 변수 설정

ROCm 경로 설정

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ export ROCM_PATH=/opt/rocm

HX 390의 890M 아키텍처 지정 (gfx1150)

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ export PYTORCH_ROCM_ARCH=gfx1150
(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ export USE_ROCM=1

HX 390의 890M 아키텍처 지정 (gfx1150)

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ export USE_CUDA=0

빌드 속도 최적화 (HX 390은 코어가 많으므로 전체 활용)

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ export MAX_JOBS=$(nproc)

# (선택) MKL 대신 OpenBLAS 등 사용 시

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ export USE_MKLDNN=1

의존성 설치

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ pip install -r requirements.txt

소스 코드 "Hipify" 수동 실행

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ python tools/amd_build/build_amd.py

빌드

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ python setup.py bdist_wheel

설치

(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ ls dist/torch-*.whl
dist/torch-2.10.0a0+git449b176-cp312-cp312-linux_x86_64.whl
(.venv) bluesanta@bluesanta-AI-Series:~/Application/Llama/pytorch$ pip install dist/torch-*.whl
728x90
728x90

xrdp 원격 데스크톱 설치

bluesanta@bluesanta-AI-Series:~$ sudo apt install xrdp

상단 상태바(Top Panel)나 도크(Dock) 보이도록 설정

bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ vi ~/.xsessionrc

내용 추가

export GNOME_SHELL_SESSION_MODE=ubuntu
export XDG_CURRENT_DESKTOP=ubuntu:GNOME
export XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/etc/xdg

GNOME 세션을 지정

bluesanta@bluesanta-AI-Series:~$ echo "gnome-session" > ~/.xsession

기본 GNOME 상태바 설정 (우측 상단 메뉴)

bluesanta@bluesanta-AI-Series:~$ sudo apt install gnome-shell-extension-manager

xrdp 내에서 GPU(Radeon 890M) 가속 활성화

bluesanta@bluesanta-AI-Series:~$ sudo adduser xrdp video
info: Adding user `xrdp' to group `video' ...
bluesanta@bluesanta-AI-Series:~$ sudo adduser xrdp render
info: Adding user `xrdp' to group `render' ...
bluesanta@bluesanta-AI-Series:~$ sudo systemctl restart xrdp

turbovnc, virtualgl 설치

bluesanta@bluesanta-AI-Series:~$ wget https://github.com/TurboVNC/turbovnc/releases/download/3.3/turbovnc_3.3_amd64.deb
bluesanta@bluesanta-AI-Series:~$ sudo dpkg -i turbovnc_3.3_amd64.deb
bluesanta@bluesanta-AI-Series:~$ wget https://github.com/VirtualGL/virtualgl/releases/download/3.1.4/VirtualGL-3.1.4.x86_64.rpm
bluesanta@bluesanta-AI-Series:~$ sudo alien -k VirtualGL-3.1.4.x86_64.rpm
bluesanta@bluesanta-AI-Series:~$ sudo dpkg -i virtualgl_3.1.4-20251007_amd64.deb 
bluesanta@bluesanta-AI-Series:~$ /opt/VirtualGL/bin/vglrun --version
VirtualGL v3.1.4 (Build 20251007)
bluesanta@bluesanta-AI-Series:~$ sudo reboot

VirtualGL 설정

bluesanta@bluesanta-AI-Series:~$ sudo /opt/VirtualGL/bin/vglserver_config
 
1) Configure server for use with VirtualGL (GLX + EGL back ends)
2) Unconfigure server for use with VirtualGL (GLX + EGL back ends)
3) Configure server for use with VirtualGL (EGL back end only)
4) Unconfigure server for use with VirtualGL (EGL back end only)
X) Exit
 
Choose:
1
 
Restrict 3D X server access to vglusers group (recommended)?
[Y/n]
n
 
Restrict framebuffer device access to vglusers group (recommended)?
[Y/n]
y
 
Disable XTEST extension (recommended)?
[Y/n]
y
... Creating /etc/modprobe.d/virtualgl.conf to set requested permissions for
    /dev/nvidia* ...
... Granting write permission to /dev/dri/card0 for vglusers group ...
chown: 부적절한 그룹: `root:vglusers'
... Granting write permission to /dev/dri/renderD128 for vglusers group ...
chown: 부적절한 그룹: `root:vglusers'
... Modifying /etc/X11/xorg.conf.d/99-virtualgl-dri.conf to enable DRI
    permissions for vglusers group ...
... /etc/gdm3/Init/Default has been saved as /etc/gdm3/Init/Default.orig.vgl ...
... Adding xhost +LOCAL: to /etc/gdm3/Init/Default script ...
... Creating /usr/share/gdm/greeter/autostart/virtualgl.desktop ...

Done. You must restart the display manager for the changes to take effect.
 
 
1) Configure server for use with VirtualGL (GLX + EGL back ends)
2) Unconfigure server for use with VirtualGL (GLX + EGL back ends)
3) Configure server for use with VirtualGL (EGL back end only)
4) Unconfigure server for use with VirtualGL (EGL back end only)
X) Exit
 
Choose:
x
bluesanta@bluesanta-AI-Series:~$ sudo reboot

TurboVNC 서버 실행

bluesanta@bluesanta-AI-Series:~$ /opt/TurboVNC/bin/vncserver :1
 
You will require a password to access your desktops.
 
Password: 
Warning: password truncated to the length of 8.
Verify:   
Would you like to enter a view-only password (y/n)? y
Password: 
Warning: password truncated to the length of 8.
Verify:   
 
Desktop 'TurboVNC: bluesanta-AI-Series:1 (bluesanta)' started on display bluesanta-AI-Series:1
 
Starting applications specified in /opt/TurboVNC/bin/xstartup.turbovnc
Log file is /home/bluesanta/.vnc/bluesanta-AI-Series:1.log
 
bluesanta@bluesanta-AI-Series:~$ echo 'export PATH=/opt/TurboVNC/bin:$PATH' >> ~/.bashrc
bluesanta@bluesanta-AI-Series:~$ source ~/.bashrc
bluesanta@bluesanta-AI-Series:~$ vncserver :1
A VNC server is already running as :1
728x90
728x90

출처

GPU 드라이버 설치

bluesanta@bluesanta-AI-Series:~$ wget https://repo.radeon.com/amdgpu-install/7.2/ubuntu/noble/amdgpu-install_7.2.70200-1_all.deb
bluesanta@bluesanta-AI-Series:~$ sudo apt install ./amdgpu-install_7.2.70200-1_all.deb
bluesanta@bluesanta-AI-Series:~$ sudo apt update
bluesanta@bluesanta-AI-Series:~$ sudo apt install "linux-headers-$(uname -r)" "linux-modules-extra-$(uname -r)"
bluesanta@bluesanta-AI-Series:~$ sudo apt install amdgpu-dkms

ROCm 설치

bluesanta@bluesanta-AI-Series:~$ sudo apt install python3-setuptools python3-wheel
bluesanta@bluesanta-AI-Series:~$ sudo usermod -a -G render,video $LOGNAME    // Add the current user to the render and video groups
bluesanta@bluesanta-AI-Series:~$ sudo apt install rocm

AMD XDNA (NPU) 통합 설치

필수 의존성 패키지 설치

bluesanta@bluesanta-AI-Series:~$ sudo apt install -y dkms git build-essential cmake libboost-all-dev libcurl4-openssl-dev libssl-dev uuid-dev libjson-c-dev libprotoc-dev

xrt-amdxdna 설치

bluesanta@bluesanta-AI-Series:~$ git clone --recursive https://github.com/amd/xdna-driver
bluesanta@bluesanta-AI-Series:~$ cd xdna-driver
bluesanta@bluesanta-AI-Series:~/xdna-driver$ cd tools
bluesanta@bluesanta-AI-Series:~/xdna-driver/tools$ sudo ./amdxdna_deps.sh
bluesanta@bluesanta-AI-Series:~/xdna-driver/tools$ cd ..
bluesanta@bluesanta-AI-Series:~/xdna-driver$ cd xrt/build
bluesanta@bluesanta-AI-Series:~/xdna-driver/xrt/build$ ./build.sh -npu -opt
  ...
CPack: Create package
CPack: - package: /home/bluesanta/xdna-driver/xrt/build/Release/xrt_202610.2.23.0_24.04-amd64-base.tar.gz generated.
CPack: - package: /home/bluesanta/xdna-driver/xrt/build/Release/xrt_202610.2.23.0_24.04-amd64-base-dev.tar.gz generated.
CPack: - package: /home/bluesanta/xdna-driver/xrt/build/Release/xrt_202610.2.23.0_24.04-amd64-npu.tar.gz generated.
 
real    0m13.628s
user    0m10.178s
sys     0m3.451s
bluesanta@bluesanta-AI-Series:~/xdna-driver/xrt/build$ sudo apt-get install ./Release/xrt_*-amd64-base.deb
bluesanta@bluesanta-AI-Series:~/xdna-driver/xrt/build$ cd ../../build
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ ./build.sh -release
  ...
CPack: Create package
CPack: - package: /home/bluesanta/xdna-driver/build/Release/xrt_plugin.2.23.0_24.04-amd64-amdxdna.deb generated.

real    0m18.222s
user    0m42.996s
sys     0m5.560s
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ sudo apt-get install ./Release/xrt_plugin.*-amdxdna.deb
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ dkms status
amdgpu/6.16.6-2238411.24.04, 6.17.0-14-generic, x86_64: installed
xrt-amdxdna/2.23.0, 6.17.0-14-generic, x86_64: installed

테스트 및 사용

NPU를 활성화

bluesanta@bluesanta-AI-Series:~/xdna-driver$ source /opt/xilinx/xrt/setup.sh
Autocomplete enabled for the xrt-smi command
XILINX_XRT        : /opt/xilinx/xrt
PATH              : /opt/xilinx/xrt/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
LD_LIBRARY_PATH   : /opt/xilinx/xrt/lib
PYTHONPATH        : /opt/xilinx/xrt/python

NPU 테스트

bluesanta@bluesanta-AI-Series:~/xdna-driver$ xrt-smi validate
WARNING: User doesn't have admin permissions to set performance mode. Running validate in Default mode
Validate Device           : [0000:c6:00.1]
    Platform              : NPU Strix
    Power Mode            : Default
-------------------------------------------------------------------------------
Test 1 [0000:c6:00.1]     : gemm 
    Details               : TOPS: 51.0                                          
    Test Status           : [PASSED]
-------------------------------------------------------------------------------
Test 2 [0000:c6:00.1]     : latency 
    Details               : Average latency: 52.0 us                            
    Test Status           : [PASSED]
-------------------------------------------------------------------------------
Test 3 [0000:c6:00.1]     : throughput 
    Details               : Average throughput: 78565.0 op/s                    
    Test Status           : [PASSED]
-------------------------------------------------------------------------------
Validation completed. Please run the command '--verbose' option for more details

설치 확인

bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ dkms status
amdgpu/6.16.13-2278356.24.04, 6.17.0-14-generic, x86_64: installed
xrt-amdxdna/2.23.0, 6.17.0-14-generic, x86_64: installed
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ mokutil --sb-state
SecureBoot disabled
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ ls -l /dev/kfd
crw-rw---- 1 root render 234, 0  2월 13 23:36 /dev/kfd
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ sudo lshw -C display
  *-display                 
       description: Display controller
       product: Advanced Micro Devices, Inc. [AMD/ATI]
       vendor: Advanced Micro Devices, Inc. [AMD/ATI]
       physical id: 0
       bus info: pci@0000:c5:00.0
       logical name: /dev/fb0
       version: c1
       width: 64 bits
       clock: 33MHz
       capabilities: pm pciexpress msi msix bus_master cap_list fb
       configuration: depth=32 driver=amdgpu latency=0 mode=3840x2160 resolution=3840,2160 visual=truecolor xres=3840 yres=2160
       resources: iomemory:780-77f irq:106 memory:7800000000-780fffffff memory:dc000000-dc1fffff ioport:e000(size=256) memory:dc500000-dc57ffff
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ rocminfo | grep "Name:"
  Name:                    AMD Ryzen AI 9 HX 370 w/ Radeon 890M
  Marketing Name:          AMD Ryzen AI 9 HX 370 w/ Radeon 890M
  Vendor Name:             CPU                                
  Name:                    gfx1150                            
  Marketing Name:          AMD Radeon Graphics                
  Vendor Name:             AMD                                
      Name:                    amdgcn-amd-amdhsa--gfx1150         
      Name:                    amdgcn-amd-amdhsa--gfx11-generic   
  Name:                    aie2p                              
  Marketing Name:          NPU Strix                          
  Vendor Name:             AMD                                
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ lsmod | grep amdgpu
amdgpu              20209664  6
amddrm_ttm_helper      12288  1 amdgpu
amdttm                131072  2 amdgpu,amddrm_ttm_helper
amddrm_buddy           28672  1 amdgpu
amdxcp                 12288  1 amdgpu
amddrm_exec            12288  1 amdgpu
drm_suballoc_helper    24576  1 amdgpu
amd_sched              65536  1 amdgpu
amdkcl                 28672  4 amd_sched,amdttm,amddrm_exec,amdgpu
drm_panel_backlight_quirks    12288  1 amdgpu
drm_display_helper    290816  1 amdgpu
cec                    98304  2 drm_display_helper,amdgpu
i2c_algo_bit           16384  1 amdgpu
drm_ttm_helper         16384  2 amdgpu
video                  77824  1 amdgpu
bluesanta@bluesanta-AI-Series:~/xdna-driver/build$ lspci | grep -i display
c5:00.0 Display controller: Advanced Micro Devices, Inc. [AMD/ATI] Device 150e (rev c1)
728x90
728x90

디스크 상세 포맷 및 파티션 구조 확인

bluesanta@bluesanta-AI-Series:~$ lsblk
NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
loop0         7:0    0     4K  1 loop /snap/bare/5
  ...
loop14        7:14   0 531.4M  1 loop /snap/gnome-42-2204/247
nvme1n1     259:0    0   1.9T  0 disk 
nvme0n1     259:1    0   1.8T  0 disk 
├─nvme0n1p1 259:2    0     1G  0 part /boot/efi
└─nvme0n1p2 259:3    0   1.8T  0 part /

디스크 상태 확인

bluesanta@bluesanta-AI-Series:/dev$ lsblk /dev/nvme1n1
NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINTS
nvme1n1 259:0    0  1.9T  0 disk 

파티션 생성 (fdisk)

  • g : GPT 파티션 테이블 생성 (2TB 이상 드라이브 권장)
  • n : 새 파티션 추가
  • Enter (Partition number: 1)
  • Enter (First sector: 기본값)
  • Enter (Last sector: 기본값 - 전체 용량 사용)
  • w : 설정 저장 및 종료
bluesanta@bluesanta-AI-Series:/dev$ sudo fdisk /dev/nvme1n1
 
Welcome to fdisk (util-linux 2.39.3).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
 
Device does not contain a recognized partition table.
Created a new DOS (MBR) disklabel with disk identifier 0x2b149640.
 
Command (m for help): p
Disk /dev/nvme1n1: 1.86 TiB, 2048408248320 bytes, 4000797360 sectors
Disk model: JAZER P3500 2TB NVMe M.2
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x2b149640
 
Command (m for help): g
Created a new GPT disklabel (GUID: 2DF2A5AF-C7BD-4750-A91B-835516230B84).
 
Command (m for help): n
Partition number (1-128, default 1): 1
First sector (2048-4000797326, default 2048): 
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-4000797326, default 4000796671): 
 
Created a new partition 1 of type 'Linux filesystem' and of size 1.9 TiB.
 
Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

포맷 (mkfs.ext4)

bluesanta@bluesanta-AI-Series:/dev$ sudo mkfs.ext4 /dev/nvme1n1p1
mke2fs 1.47.0 (5-Feb-2023)
Discarding device blocks: done                            
Creating filesystem with 500099328 4k blocks and 125026304 inodes
Filesystem UUID: 5d5c123d-b1e7-4a57-80b6-8bb577431383
Superblock backups stored on blocks: 
        32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 
        4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968, 
        102400000, 214990848
 
Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (262144 blocks): done
Writing superblocks and filesystem accounting information: done       

마운트 포인트 생성 및 연결

bluesanta@bluesanta-AI-Series:/dev$ sudo mkdir /bluesanta
bluesanta@bluesanta-AI-Series:/dev$ sudo mount /dev/nvme1n1p1 /bluesanta/

부팅 시 자동 마운트 설정 (UUID)

UUID 확인

bluesanta@bluesanta-AI-Series:/bluesanta$ sudo blkid /dev/nvme1n1p1
/dev/nvme1n1p1: UUID="5d5c123d-b1e7-4a57-80b6-8bb577431383" BLOCK_SIZE="4096" TYPE="ext4" PARTUUID="84b0122a-b8ff-4ed6-a052-14bff6fc2509"

fstab 수정

bluesanta@bluesanta-AI-Series:/bluesanta$ sudo vi /etc/fstab

파일 맨 아래에 한 줄을 추가

UUID=5d5c123d-b1e7-4a57-80b6-8bb577431383  /bluesanta  ext4  defaults  0  2
728x90
728x90

기존 CMake 삭제

bluesanta@bluesanta-desktop:~$ sudo apt remove --purge cmake

빌드 관련 패키지 설치

bluesanta@bluesanta-desktop:~$ sudo apt install build-essential libssl-dev

CMake 3.26.4 다운로드 및 설치

bluesanta@bluesanta-desktop:~$ wget https://github.com/Kitware/CMake/releases/download/v3.26.4/cmake-3.26.4-linux-x86_64.sh
bluesanta@bluesanta-desktop:~$ sudo sh cmake-3.26.4-linux-x86_64.sh --prefix=/usr/local --exclude-subdir

설치 확인

bluesanta@bluesanta-desktop:~$ cmake --version
cmake version 3.26.4
 
CMake suite maintained and supported by Kitware (kitware.com/cmake).
728x90
728x90

ApiApplication

package com.bx.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ApiApplication {

	public static void main(String[] args) {
		SpringApplication.run(ApiApplication.class, args);
	}
}

application.properties

# RabbitMQ (RK3588 IP)
spring.rabbitmq.host=192.168.0.24
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=password

Topic의 핵심: 와일드카드(Wildcards)

Topic 방식의 가장 큰 특징은 **점(.)**으로 구분된 라우팅 키와 두 가지 특수 기호를 사용할 수 있다는 점입니다.

  • * (별표): 정확히 단어 하나를 대체합니다. (예: *.orange.*)
  • # (우물 정): 0개 이상의 단어를 대체합니다. (예: lazy.#)

RabbitTopicConfig

Spring Boot에서 Topic 방식을 쓰려면 TopicExchange와 Binding을 설정

package com.bx.api.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitTopicConfig {

	// 1. Topic 타입의 Exchange 생성
	@Bean
	public TopicExchange topicExchange() {
		return new TopicExchange("log.exchange");
	}

	// 2. 큐 생성
	@Bean
	public Queue errorQueue() {
		return new Queue("error.queue");
	}

	// 3. 바인딩 (에러 로그만 이 큐로 오게 설정)
	@Bean
	public Binding bindingError(Queue errorQueue, TopicExchange topicExchange) {
		// "#.error" 패턴을 가진 메시지만 errorQueue로 연결
		return BindingBuilder.bind(errorQueue).to(topicExchange).with("#.error");
	}

	@Bean
	public MessageConverter jsonMessageConverter() {
		// 이 설정이 있어야 객체 <-> JSON 변환이 가능합니다.
		return new Jackson2JsonMessageConverter();
	}
}

TopicConfig

Topic 방식은 Exchange, Queue, Binding 정의

package com.bx.api.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TopicConfig {

	public static final String EXCHANGE_NAME = "log.topic.exchange";
	public static final String ALL_LOG_QUEUE = "all.log.queue";
	public static final String ERROR_LOG_QUEUE = "error.log.queue";

	// 1. Topic Exchange 선언
	@Bean
	public TopicExchange logExchange() {
		return new TopicExchange(EXCHANGE_NAME);
	}

	// 2. 큐 선언 (모든 로그용 / 에러 전용)
	@Bean
	public Queue allLogQueue() {
		return new Queue(ALL_LOG_QUEUE);
	}

	@Bean
	public Queue errorLogQueue() {
		return new Queue(ERROR_LOG_QUEUE);
	}

	// 3. 바인딩 (와일드카드 사용)
	@Bean
	public Binding bindAll(Queue allLogQueue, TopicExchange logExchange) {
		// "seoul.#" -> 서울에서 발생하는 모든 로그(info, warn, error 등) 수집
		return BindingBuilder.bind(allLogQueue).to(logExchange).with("seoul.#");
	}

	@Bean
	public Binding bindError(Queue errorLogQueue, TopicExchange logExchange) {
		// "#.error" -> 지역 상관없이 모든 에러 로그만 수집
		return BindingBuilder.bind(errorLogQueue).to(logExchange).with("#.error");
	}
}

메시지 보내기 (Producer) : LogProducer

package com.bx.api.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import com.bx.api.config.TopicConfig;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class LogProducer {

	private final RabbitTemplate rabbitTemplate;

	public void sendLog(String location, String level, String message) {
		// 라우팅 키 생성 예: "seoul.info" 또는 "busan.error"
		String routingKey = location + "." + level;

		Map<String, String> logData = new HashMap<>();
		logData.put("location", location);
		logData.put("level", level);
		logData.put("message", message);

		rabbitTemplate.convertAndSend(TopicConfig.EXCHANGE_NAME, routingKey, logData);
		System.out.println("Sent Log with Key [" + routingKey + "]: " + message);
	}
}

메시지 받기 (Consumer) : LogConsumer

package com.bx.api.service;

import java.util.Map;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import com.bx.api.config.TopicConfig;

@Service
public class LogConsumer {

	// 서울 지역의 모든 로그 처리
	@RabbitListener(queues = TopicConfig.ALL_LOG_QUEUE)
	public void consumeAllSeoulLog(Map<String, String> message) {
		System.out.println("[서울 통합 관제센터] 수신: " + message);
	}

	// 전 지역의 에러 로그만 처리
	@RabbitListener(queues = TopicConfig.ERROR_LOG_QUEUE)
	public void consumeErrorLog(Map<String, String> message) {
		System.out.println("[긴급 에러 알람] 수신: " + message);
	}
}

로그 메시지 전송용 Controller 구현

package com.bx.api.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bx.api.service.LogProducer;

import lombok.RequiredArgsConstructor;

@RestController
@RequiredArgsConstructor
public class RabbitController {

	private final LogProducer logProducer;

	/**
	 * HTTP GET 호출을 받아 RabbitMQ로 메시지 전송 실행 주소:
	 * http://localhost:8080/send?loc=seoul&lvl=info&msg=test_message
	 */
	@GetMapping("/send")
	public Map<String, Object> sendMessage(@RequestParam(value = "loc") String location,
			@RequestParam(value = "lvl") String level, @RequestParam(value = "msg") String message) {

		// 이전에 만든 Producer의 메서드 호출
		logProducer.sendLog(location, level, message);

		Map<String, Object> result = new HashMap<>();
		result.put("status", "success");
		result.put("routingKey", location + "." + level);
		result.put("payload", message);

		return result;
	}
}

실행

메시지 전송

호출 주소 예제

http://192.168.0.4:8080/send?loc=seoul&lvl=info&msg=test_message

서버 로그

Sent Log with Key [seoul.info]: test_message
[서울 통합 관제센터] 수신: {level=info, location=seoul, message=test_message}
728x90

+ Recent posts