RedisPubSubController.java 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package com.ruoyi.demo.controller;
  2. import com.ruoyi.common.core.domain.R;
  3. import com.ruoyi.common.redis.utils.RedisUtils;
  4. import lombok.RequiredArgsConstructor;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * Redis 发布订阅 演示案例
  10. *
  11. * @author Lion Li
  12. */
  13. @RequiredArgsConstructor
  14. @RestController
  15. @RequestMapping("/demo/redis/pubsub")
  16. public class RedisPubSubController {
  17. /**
  18. * 发布消息
  19. *
  20. * @param key 通道Key
  21. * @param value 发送内容
  22. */
  23. @GetMapping("/pub")
  24. public R<Void> pub(String key, String value) {
  25. RedisUtils.publish(key, value, consumer -> {
  26. System.out.println("发布通道 => " + key + ", 发送值 => " + value);
  27. });
  28. return R.ok("操作成功");
  29. }
  30. /**
  31. * 订阅消息
  32. *
  33. * @param key 通道Key
  34. */
  35. @GetMapping("/sub")
  36. public R<Void> sub(String key) {
  37. RedisUtils.subscribe(key, String.class, msg -> {
  38. System.out.println("订阅通道 => " + key + ", 接收值 => " + msg);
  39. });
  40. return R.ok("操作成功");
  41. }
  42. }