1.创建一个 UserController 控制器类,处理 HTTP 请求和 socket 连接,并实现用户之间的实时通信。
@RestController
public class UserController {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private HBaseTemplate hbaseTemplate;
@MessageMapping("/chat")
@SendTo("/topic/messages")
public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
String username = chatMessage.getSender();
String message = chatMessage.getContent();
saveMessageToDB(username, message);
saveMessageToHBase(username, message);
saveMessageToRedis(username, message);
return chatMessage;
}
private void saveMessageToDB(String username, String message) {
String sql = "INSERT INTO messages (username, message) VALUES (?, ?)";
jdbcTemplate.update(sql, username, message);
}
private void saveMessageToHBase(String username, String message) {
String tableName = "messages";
String rowKey = UUID.randomUUID().toString();
String family = "cf";
String qualifier1 = "username";
String value1 = username;
String qualifier2 = "message";
String value2 = message;
Put put = new Put(Bytes.toBytes(rowKey));
put.addColumn(Bytes.toBytes(family),