{"id":21672562,"url":"https://github.com/redis-developer/basic-redis-chat-app-demo-java","last_synced_at":"2025-04-12T03:53:11.171Z","repository":{"id":41817067,"uuid":"336142847","full_name":"redis-developer/basic-redis-chat-app-demo-java","owner":"redis-developer","description":"A sample redis chat demo app written in Java","archived":false,"fork":false,"pushed_at":"2023-06-27T07:24:07.000Z","size":4125,"stargazers_count":25,"open_issues_count":1,"forks_count":25,"subscribers_count":6,"default_branch":"main","last_synced_at":"2025-04-12T03:53:05.750Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/redis-developer.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-02-05T02:37:02.000Z","updated_at":"2025-03-03T10:32:11.000Z","dependencies_parsed_at":"2022-08-11T18:20:53.312Z","dependency_job_id":null,"html_url":"https://github.com/redis-developer/basic-redis-chat-app-demo-java","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fbasic-redis-chat-app-demo-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fbasic-redis-chat-app-demo-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fbasic-redis-chat-app-demo-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/redis-developer%2Fbasic-redis-chat-app-demo-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/redis-developer","download_url":"https://codeload.github.com/redis-developer/basic-redis-chat-app-demo-java/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248514209,"owners_count":21116899,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-25T13:30:06.635Z","updated_at":"2025-04-12T03:53:11.150Z","avatar_url":"https://github.com/redis-developer.png","language":"JavaScript","readme":"# Basic Redis Chat App Demo (Java/Spring)\n\nShowcases how to implement chat app in Java (Spring Boot) and Redis. This example uses **pub/sub** feature combined with **server-side events** for implementing the message communication between client and server.\n\n\u003ca href=\"https://github.com/redis-developer/basic-redis-chat-app-demo-java/raw/main/docs/screenshot000.png\"\u003e\u003cimg src=\"https://github.com/redis-developer/basic-redis-chat-app-demo-java/raw/main/docs/screenshot000.png\" width=\"49%\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/redis-developer/basic-redis-chat-app-demo-java/raw/main/docs/screenshot001.png\"\u003e\u003cimg src=\"https://github.com/redis-developer/basic-redis-chat-app-demo-java/raw/main/docs/screenshot001.png\" width=\"49%\"\u003e\u003c/a\u003e\n\n# Overview video\n\nHere's a short video that explains the project and how it uses Redis:\n\n[![Watch the video on YouTube](https://github.com/redis-developer/basic-redis-chat-app-demo-java/raw/main/docs/YTThumbnail.png)](https://www.youtube.com/watch?v=miK7xDkDXF0)\n\n## Technical Stacks\n\n- Frontend - _React_, _Server-sent events_\n- Backend - _Spring Boot 2_, _Redis_\n\n## How it works?\n\n## Database Schema\n\n### User\n\n```Java\npublic class User {\n  private int id;\n  private String username;\n  private boolean isOnline;\n}\n```\n\n### ChatRoom\n\n```Java\npublic class Room {\n  private String id;\n  private String[] names;\n}\n```\n\n### ChatRoomMessage\n\n```Java\npublic class Message {\n  private String from;\n  private int date;\n  private String message;\n  private String roomId;\n}\n```\n\n### Initialization\n\nFor simplicity, a key with **total_users** value is checked: if it does not exist, we fill the Redis database with initial data.\n`EXISTS total_users` (checks if the key exists)\n\nThe demo data initialization is handled in multiple steps:\n\n**Creating of demo users:**\nWe create a new user id: `INCR total_users`. Then we set a user ID lookup key by user name: **_e.g._** `SET username:nick user:1`. And finally, the rest of the data is written to the hash set: **_e.g._** `HSET user:1 username \"nick\" password \"bcrypt_hashed_password\"`.\n\nAdditionally, each user is added to the default \"General\" room. For handling rooms for each user, we have a set that holds the room ids. Here's an example command of how to add the room: **_e.g._** `SADD user:1:rooms \"0\"`.\n\n**Populate private messages between users.**\nAt first, private rooms are created: if a private room needs to be established, for each user a room id: `room:1:2` is generated, where numbers correspond to the user ids in ascending order.\n\n**_E.g._** Create a private room between 2 users: `SADD user:1:rooms 1:2` and `SADD user:2:rooms 1:2`.\n\nThen we add messages to this room by writing to a sorted set:\n\n**_E.g._** `ZADD room:1:2 1615480369 \"{'from': 1, 'date': 1615480369, 'message': 'Hello', 'roomId': '1:2'}\"`.\n\nWe use a stringified _JSON_ for keeping the message structure and simplify the implementation details for this demo-app.\n\n**Populate the \"General\" room with messages.** Messages are added to the sorted set with id of the \"General\" room: `room:0`\n\n### Registration\n\n![How it works](docs/screenshot000.png)\n\nRedis is used mainly as a database to keep the user/messages data and for sending messages between connected servers.\n\n#### How the data is stored:\n\n- The chat data is stored in various keys and various data types.\n  - User data is stored in a hash set where each user entry contains the next values:\n    - `username`: unique user name;\n    - `password`: hashed password\n\n* User hash set is accessed by key `user:{userId}`. The data for it stored with `HSET key field data`. User id is calculated by incrementing the `total_users`.\n\n  - E.g `INCR total_users`\n\n* Username is stored as a separate key (`username:{username}`) which returns the userId for quicker access.\n  - E.g `SET username:Alex 4`\n\n#### How the data is accessed:\n\n- **Get User** `HGETALL user:{id}`\n\n  - E.g `HGETALL user:2`, where we get data for the user with id: 2.\n\n- **Online users:** will return ids of users which are online\n  - E.g `SMEMBERS online_users`\n\n#### Code Example: Prepare User Data in Redis HashSet\n\n```Java\npublic class DemoDataCreator {\n\n    //...\n\n    private User createUser(String username) {\n        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();\n        String usernameKey = String.format(\"username:%s\", username);\n\n        // Yeah, bcrypt generally ins't used in .NET, this one is mainly added to be compatible with Node and Python demo servers.\n        String hashedPassword = encoder.encode(DEMO_PASSWORD);\n\n        Integer nextId = redisTemplate.opsForValue().increment(\"total_users\").intValue();\n        String userKey = String.format(\"user:%s\", nextId);\n\n        redisTemplate.opsForValue().set(usernameKey, userKey);\n        redisTemplate.opsForHash().put(userKey, \"username\", username);\n        redisTemplate.opsForHash().put(userKey, \"password\", hashedPassword);\n\n        String roomsKey = String.format(\"user:%s:rooms\", nextId);\n        redisTemplate.opsForSet().add(roomsKey, \"0\");\n\n        return new User(\n                nextId,\n                username,\n                false\n        );\n    }\n    //...\n}\n```\n\n### Rooms\n\n![How it works](docs/screenshot001.png)\n\n#### How the data is stored:\n\nEach user has a set of rooms associated with them.\n\n**Rooms** are sorted sets which contains messages where score is the timestamp for each message. Each room has a name associated with it.\n\n- Rooms which user belongs too are stored at `user:{userId}:rooms` as a set of room ids.\n\n  - E.g `SADD user:Alex:rooms 1`\n\n- Set room name: `SET room:{roomId}:name {name}`\n  - E.g `SET room:1:name General`\n\n#### How the data is accessed:\n\n- **Get room name** `GET room:{roomId}:name`.\n\n  - E. g `GET room:0:name`. This should return \"General\"\n\n- **Get room ids of a user:** `SMEMBERS user:{id}:rooms`.\n  - E. g `SMEMBERS user:2:rooms`. This will return IDs of rooms for user with ID: 2\n\n#### Code Example: Get all My Rooms\n\n```Java\n@RestController\n@RequestMapping(\"/rooms\")\npublic class RoomsController {\n\n    //...\n\n    @GetMapping(value = \"user/{userId}\", produces = MediaType.APPLICATION_JSON_VALUE)\n    public ResponseEntity\u003cList\u003cRoom\u003e\u003e getRooms(@PathVariable int userId) {\n        Set\u003cString\u003e roomIds = roomsRepository.getUserRoomIds(userId);\n        if (roomIds == null) {\n            return new ResponseEntity\u003c\u003e(HttpStatus.BAD_REQUEST);\n        }\n        List\u003cRoom\u003e rooms = new ArrayList\u003c\u003e();\n\n        for (String roomId : roomIds) {\n            boolean roomExists = roomsRepository.isRoomExists(roomId);\n            if (roomExists) {\n                String name = roomsRepository.getRoomNameById(roomId);\n                if (name == null) {\n                    // private chat case\n                    Room privateRoom = handlePrivateRoomCase(roomId);\n                    if (privateRoom == null) {\n                        return new ResponseEntity\u003c\u003e(HttpStatus.INTERNAL_SERVER_ERROR);\n                    }\n                    rooms.add(privateRoom);\n                } else {\n                    rooms.add(new Room(roomId, name));\n                }\n            }\n        }\n        return new ResponseEntity\u003c\u003e(rooms, HttpStatus.OK);\n    }\n    //...\n}\n```\n\n### Messages\n\n#### Pub/sub\n\nAfter initialization, a pub/sub subscription is created: `SUBSCRIBE MESSAGES`. At the same time, each server instance will run a listener on a message on this channel to receive real-time updates.\n\nAgain, for simplicity, each message is serialized to **_JSON_**, which we parse and then handle in the same manner, as WebSocket messages.\n\nPub/sub allows connecting multiple servers written in different platforms without taking into consideration the implementation detail of each server.\n\n#### How the data is stored:\n\n- Messages are stored at `room:{roomId}` key in a sorted set (as mentioned above). They are added with `ZADD room:{roomId} {timestamp} {message}` command. Message is serialized to an app-specific JSON string.\n  - E.g `ZADD room:0 1617197047 { \"From\": \"2\", \"Date\": 1617197047, \"Message\": \"Hello\", \"RoomId\": \"1:2\" }`\n\n#### How the data is accessed:\n\n- **Get list of messages** `ZREVRANGE room:{roomId} {offset_start} {offset_end}`.\n  - E.g `ZREVRANGE room:1:2 0 50` will return 50 messages with 0 offsets for the private room between users with IDs 1 and 2.\n\n#### Code Example: Send Message\n\n```Java\n@RestController\n@RequestMapping(\"/chat\")\npublic class ChatController {\n  @RequestMapping(\"/stream\")\n  public SseEmitter streamSseMvc(@RequestParam int userId) {\n    AtomicBoolean isComplete = new AtomicBoolean(false);\n    SseEmitter emitter = new SseEmitter();\n\n    Function\u003cString, Integer\u003e handler = (String message) -\u003e {\n      SseEmitter.SseEventBuilder event = SseEmitter.event()\n              .data(message);\n      try {\n        emitter.send(event);\n      } catch (IOException e) {\n        // This may occur when the client was disconnected.\n        return 1;\n      }\n      return 0;\n    };\n\n    // RedisMessageSubscriber is a global class which subscribes to the \"MESSAGES\" channel\n    // However once the /stream endpoint is invoked, it's necessary to notify the global subscriber\n    // that such client-server subscription exists.\n    //\n    // We send the callback to the subscriber with the SSE instance for sending server-side events.\n    RedisMessageSubscriber redisMessageSubscriber = (RedisMessageSubscriber) messageListener.getDelegate();\n    redisMessageSubscriber.attach(handler);\n\n    // Make sure all life-time methods are covered here and remove the handler from the global subscriber.\n    Runnable onDetach = () -\u003e {\n      redisMessageSubscriber.detach(handler);\n      if (!isComplete.get()) {\n        isComplete.set(true);\n        emitter.complete();\n      }\n    };\n\n    emitter.onCompletion(onDetach);\n    emitter.onError((err) -\u003e onDetach.run());\n    emitter.onTimeout(onDetach);\n\n    return emitter;\n  }\n}\n```\n\n### Session handling\n\nThe chat server works as a basic _REST_ API which involves keeping the session and handling the user state in the chat rooms (besides the WebSocket/real-time part).\n\nWhen a WebSocket/real-time server is instantiated, which listens for the next events:\n\n**Connection**. A new user is connected. At this point, a user ID is captured and saved to the session (which is cached in Redis). Note, that session caching is language/library-specific and it's used here purely for persistence and maintaining the state between server reloads.\n\nA global set with `online_users` key is used for keeping the online state for each user. So on a new connection, a user ID is written to that set:\n\n**E.g.** `SADD online_users 1` (We add user with id 1 to the set **online_users**).\n\nAfter that, a message is broadcasted to the clients to notify them that a new user is joined the chat.\n\n**Disconnect**. It works similarly to the connection event, except we need to remove the user for **online_users** set and notify the clients: `SREM online_users 1` (makes user with id 1 offline).\n\n**Message**. A user sends a message, and it needs to be broadcasted to the other clients. The pub/sub allows us also to broadcast this message to all server instances which are connected to this Redis:\n\n`PUBLISH message \"{'serverId': 4132, 'type':'message', 'data': {'from': 1, 'date': 1615480369, 'message': 'Hello', 'roomId': '1:2'}}\"`\n\nNote we send additional data related to the type of the message and the server id. Server id is used to discard the messages by the server instance which sends them since it is connected to the same `MESSAGES` channel.\n\n`type` field of the serialized JSON corresponds to the real-time method we use for real-time communication (connect/disconnect/message).\n\n`data` is method-specific information. In the example above it's related to the new message.\n\n#### How the data is stored / accessed:\n\nThe session data is stored in Redis by utilizing the [**Letuce**](https://github.com/lettuce-io/lettuce-core) client.\n\n##### Startup\n\n```Java\npublic class RedisAppConfig {\n\n    //...\n\n    public RedisConnectionFactory redisConnectionFactory() {\n        // Read environment variables\n        String endpointUrl = System.getenv(\"REDIS_ENDPOINT_URL\");\n        if (endpointUrl == null) {\n            endpointUrl = \"127.0.0.1:6379\";\n        }\n        String password = System.getenv(\"REDIS_PASSWORD\");\n\n        String[] urlParts = endpointUrl.split(\":\");\n\n        String host = urlParts[0];\n        String port = \"6379\";\n\n        if (urlParts.length \u003e 1) {\n            port = urlParts[1];\n        }\n\n        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, Integer.parseInt(port));\n\n        System.out.printf(\"Connecting to %s:%s with password: %s%n\", host, port, password);\n\n        if (password != null) {\n            config.setPassword(password);\n        }\n        return new LettuceConnectionFactory(config);\n    }\n}\n```\n\n## How to run it locally?\n\n#### Set the Redis endpoint and password environment variables:\n\n```\n$ REDIS_ENDPOINT_URL=localhost:6379\n$ REDIS_PASSWORD=foo\n```\n\nNote that the `REDIS_PASSWORD` variable is required only if your connecting to a password-protected Redis instance.\n\n#### Run App\n\nEnsure that you have Maven wrapper installed:\n\n```sh\nmvn -N io.takari:maven:wrapper\n```\n\nThe start the application:\n```sh\n./mvnw spring-boot:run\n```\n\nTo interact with the application, point your browser to `localhost:8080`.\n\n#### Run Frontend\n\nThe client is bundled with the server by default, however it's possible to run the client separately for development:\n\n```sh\ncd client\nyarn install\nyarn start\n```\n\n## Try it out\n\n#### Deploy to Heroku\n\n\u003cp\u003e\n    \u003ca href=\"https://heroku.com/deploy\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://www.herokucdn.com/deploy/button.svg\" alt=\"Deploy to Heroku\" /\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n#### Deploy to Google Cloud\n\n\u003cp\u003e\n    \u003ca href=\"https://deploy.cloud.run\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://deploy.cloud.run/button.svg\" alt=\"Run on Google Cloud\" width=\"150px\"/\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredis-developer%2Fbasic-redis-chat-app-demo-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fredis-developer%2Fbasic-redis-chat-app-demo-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fredis-developer%2Fbasic-redis-chat-app-demo-java/lists"}