practice-publish-signup-event
✅ 사용자 서비스에서 Kafka로 ‘회원가입 완료 이벤트’ 발행하기 게시글 서비스에서 사용해야 하는 사용자 데이터(user_id, name)를 동기화하기 위해서, 사용자 서비스에서 user_id, name의 데이터가 생성/변경/삭제가 될 때마다 카프카로 이벤트를 발행 해주어야 한다. 현재 프로젝트에서는 사용자 데이터를 생성 하는 회원가입 API가 구현되어 있다. 따라서 데이터 동기화를 위해 회원가입 API에 이벤트 발행 로직을 추가해보자.
✅ 코드 작성하기 user-service에서 아래 코드 작성하기
application.yml에 Kafka 설정 추가해주기 server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/user-db
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
kafka:
# Kafka 서버 주소
bootstrap-servers: localhost:9092
consumer:
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
client:
point-service:
url: http://localhost:8082
Kafka로 전달할 메시지 객체 만들기 event/UserSignedUpEvent
public class UserSignedUpEvent {
private Long userId;
private String name;
public UserSignedUpEvent(Long userId, String name) {
this.userId = userId;
this.name = name;
}
public Long getUserId() {
return userId;
}
public String getName() {
return name;
}
}
회원 가입을 완료하는 대로 Kafka 메시지 발행하도록 처리하기 service/UserService
@Service
public class UserService {
private final UserRepository userRepository;
private final PointClient pointClient;
private final KafkaTemplate<String, String> kafkaTemplate;
public UserService(UserRepository userRepository,
PointClient pointClient,
KafkaTemplate<String, String> kafkaTemplate) {
this.userRepository = userRepository;
this.pointClient = pointClient;
this.kafkaTemplate = kafkaTemplate;
}
@Transactional
public void signUp(SignUpRequestDto signUpRequestDto) {
User user = new User(
signUpRequestDto.getEmail(),
signUpRequestDto.getName(),
signUpRequestDto.getPassword()
);
User savedUser = this.userRepository.save(user);
// 회원가입하면 포인트 1000점 적립
pointClient.addPoints(savedUser.getUserId(), 1000);
// '회원가입 완료' 이벤트 발행
UserSignedUpEvent userSignedUpEvent = new UserSignedUpEvent(
savedUser.getUserId(),
savedUser.getName()
);
this.kafkaTemplate.send(
"user.signed-up",
toJsonString(userSignedUpEvent)
);
}
// 객체를 Json 형태의 String으로 만들어주는 메서드
// (클래스로 분리하면 더 좋지만 편의를 위해 메서드로만 분리)
private String toJsonString(Object object) {
ObjectMapper objectMapper = new ObjectMapper();
try {
String message = objectMapper.writeValueAsString(object);
return message;
} catch (JsonProcessingException e) {
throw new RuntimeException("Json 직렬화 실패");
}
}
...
}
서버 다시 실행시키기