최근 팀 커뮤니케이션으로 많은 사람들의 사랑을 받고 있는 슬랙(Slack).
슬랙에서는 외부에서 슬랙채널에 메시지를 보낼 수 있는 WebHook API를 제공하고 있다. 웹훅은 슬랙으로 데이터를 보내는 Incoming WebHook 과 특정조건에 부합되었을 때 외부의 데이터를 가져오는 Outgoing WebHook 이 있다.
웹애플리케이션에서 슬랙채널로 메시지를 보내는 것은 Incoming WebHook을 이용하게 된다.
그러기 위해서는 우선 팀슬랙에 Incomming WebHook을 설정한다.
| NOTE | 
 | 
Slack: Incoming WebHook 설정
작업을 진행하기에 앞서서 채널을 하나 개설한다. 그후 통합Integration 으로 이동하여 'incoming webhook' 을 검색하여 설치하고 채널을 지정한다. 필요하다면 아이콘을 변경하는 작업을 한다. 화면에 나오는 웹훅 URL 을 복사해둔다.
스프링부트 프로젝트 생성
스프링부트 프로젝트를 생성한다.
build.gradlebuildscript {
	ext {
		springBootVersion = '1.3.5.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
jar {
	baseName = 'slack-incoming-webhook'
	version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
	mavenCentral()
}
dependencies {
	compile('org.projectlombok:lombok:1.16.8')
	compile('org.springframework.boot:spring-boot-starter-web')
	compile('com.google.guava:guava:19.0')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}RestTemplate 빈 선언
WebConfigurationpackage io.honeymon.springboot.slack.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class WebConfiguration {
	@Bean
	RestTemplate restTemplate() {
		return new RestTemplate();
	}
}SlackNotifier 컴포넌트 생성
SlackNotifierpackage io.honeymon.springboot.slack.integration;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
 * Slack Notifier
 *
 * @author honeymon
 *
 */
@Slf4j
@Component
public class SlackNotifier {
	@Autowired
	private RestTemplate restTemplate;
	public enum SlackTarget {
		// TODO webHookUrl 은 자신의 슬랙 IncomingWebHookAPI로 변경하세요.
		CH_INCOMING("https://hooks.slack.com/services/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", "incoming");
		String webHookUrl;
		String channel;
		SlackTarget(String webHookUrl, String channel) {
			this.webHookUrl = webHookUrl;
			this.channel = channel;
		}
	}
	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	@Builder
	public static class SlackMessageAttachement {
		private String color;
		private String pretext;
		private String title;
		private String title_link;
		private String text;
	}
	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	@Builder
	public static class SlackMessage {
		private String text;
		private String channel;
		private List<SlackMessageAttachement> attachments;
		void addAttachment(SlackMessageAttachement attachement) {
			if (this.attachments == null) {
				this.attachments = Lists.newArrayList();
			}
			this.attachments.add(attachement);
		}
	}
	public boolean notify(SlackTarget target, SlackMessageAttachement message) {
		log.debug("Notify[target: {}, message: {}]", target, message);
		SlackMessage slackMessage = SlackMessage.builder().channel(target.channel)
				.attachments(Lists.newArrayList(message)).build();
		try {
			restTemplate.postForEntity(target.webHookUrl, slackMessage, String.class);
			return true;
		} catch (Exception e) {
			log.error("Occur Exception: {}", e);
			return false;
		}
	}
}SlackController 생성
SlackSenderControllerpackage io.honeymon.springboot.slack.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.honeymon.springboot.slack.integration.SlackNotifier;
import io.honeymon.springboot.slack.integration.SlackNotifier.SlackMessageAttachement;
import io.honeymon.springboot.slack.integration.SlackNotifier.SlackTarget;
@RestController
public class SlackSendController {
	@Autowired
	private SlackNotifier slackNotifier;
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public ResponseEntity<Boolean> send(@RequestBody SlackMessageAttachement message) {  (1)
		return ResponseEntity.ok(slackNotifier.notify(SlackTarget.CH_INCOMING, message));
	}
}- POST ` 방식으로 전송을 할 때 `@RequestBody로 클래스를 정의하면 자동으로 매핑된다.
slack-incoming-webhook 실행
$ git clone https://github.com/ihoneymon/slack-incoming-webhook
$ cd slack-incoming-webhook
$ ./gradlew springboot포스트맨을 이용한 실행 확인
실제 슬랙 화면
팀채널로 많이 사용하는 슬랙.
배포한 앱에서 중요한 사항(항상 상태를 체크해야하는 상황)에 대해서 슬랙 채널로 공지하도록 하는 기능을 간단하게 구현해봤다. @_@)> 생각보다 쉽다. 많이.
예제에서는 컨트롤러에서 요청을 받아서 처리하는 방식으로 구현했다.
'Java > SpringBoot' 카테고리의 다른 글
| 부트 스프링 부트(Boot Spring Boot) 쓰기 시작 (2) | 2016.08.07 | 
|---|---|
| [springboot] 스프링부트 개발가이드 작성 시작 (0) | 2016.07.21 | 
| [springboot] 앱 프로세스ID(pid) 관리 (0) | 2016.04.07 | 
| [스프링부트] 빌드시 깃 커밋버전 정보 포함시키기 (0) | 2016.02.26 | 
| [스프링부트] 생성물 위치 (0) | 2016.02.24 |