### User Service API Examples (Bash) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Provides command-line examples using curl to interact with the User Service API. Demonstrates creating a user, retrieving a user by ID, and retrieving a user by username. ```bash # Create a new user curl -X POST http://localhost:8206/user/create \ -H "Content-Type: application/json" \ -d '{"id": 1, "username": "admin", "password": "123456"}' # Response: # {"message": "Operation successful", "code": 200} # Get user by ID curl http://localhost:8206/user/1 # Response: # {"data": {"id": 1, "username": "admin", "password": "123456"}, "code": 200} # Get user by username curl "http://localhost:8206/user/getByUsername?username=admin" ``` -------------------------------- ### OAuth2 Authorization Server Command-Line Example (Bash) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Provides a command-line instruction to initiate the authorization code flow for the configured OAuth2 server. This is the first step in obtaining an authorization code, which is then used to get access and refresh tokens. ```bash # Authorization code flow - Step 1: Get authorization code ``` -------------------------------- ### Resilience4j Command-Line Examples (Bash) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Provides example curl commands to test the Resilience4j patterns implemented in the Java controller. These commands demonstrate how to trigger the circuit breaker, retry with fallback, and rate limiter functionalities, showing expected outputs or error responses. ```bash # Circuit breaker in action curl http://localhost:8305/breaker/circleBreakerApi/1 # Retry with fallback when service fails curl http://localhost:8305/breaker/retryApi/1 # After retries exhausted: # {"data": {"id": -1, "username": "defaultUser"}, "message": "Connection refused", "code": 200} # Rate limiter curl http://localhost:8305/breaker/rateLimiterApi/1 # When rate exceeded: HTTP 429 Too Many Requests ``` -------------------------------- ### Sentinel Rate Limiting Request Examples (Bash) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Provides bash commands to test Sentinel rate limiting. It shows a normal request and the response after exceeding the rate limit, along with an example of configuring rate limiting rules via the Sentinel API. ```bash # Normal request curl http://localhost:8401/rateLimit/byResource # {"message": "Rate limited by resource name", "code": 200} # After exceeding rate limit (configured in Sentinel dashboard) curl http://localhost:8401/rateLimit/byResource # {"message": "com.alibaba.csp.sentinel.slots.block.flow.FlowException", "code": 429} # Configure rate limiting rules via Sentinel dashboard or API curl -X POST http://localhost:8080/v1/flow/rules \ -H "Content-Type: application/json" \ -d '[{"resource":"byResource","grade":1,"count":5,"strategy":0,"controlBehavior":0}]' ``` -------------------------------- ### OpenFeign Service Call Example (Bash) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Demonstrates calling a service that uses OpenFeign to communicate with another service. Shows a curl command to invoke the Feign client endpoint and expected responses for both successful calls and fallback scenarios. ```bash # Call feign-service which invokes nacos-user-service via Feign curl http://localhost:8308/user/1 # Response (from actual service): # {"data": {"id": 1, "username": "admin", "password": "123456"}, "code": 200} # Response (fallback when service unavailable): ``` -------------------------------- ### Spring Cloud Gateway Configuration Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Configuration examples for Spring Cloud Gateway, including basic routing, Nacos discovery, and route filtering. ```APIDOC ## Spring Cloud Gateway Configuration ### Description API Gateway configuration with route predicates and load balancing for microservices. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters N/A ### Request Example ```yaml # application.yml for gateway-service server: port: 9201 service-url: user-service: http://localhost:8206 logging: level: org.springframework.cloud.gateway: debug spring: application: name: gateway-service cloud: gateway: routes: - id: path_route # Route identifier uri: ${service-url.user-service}/user/{id} # Target URI predicates: # Route matching conditions - Path=/user/{id} ``` ```yaml # Advanced gateway configuration with Nacos discovery and Knife4j spring: cloud: nacos: discovery: server-addr: localhost:8848 gateway: routes: - id: user-service uri: lb://micro-knife4j-user # Load-balanced URI predicates: - Path=/user-service/** filters: - StripPrefix=1 # Remove prefix before forwarding - id: order-service uri: lb://micro-knife4j-order predicates: - Path=/order-service/** filters: - StripPrefix=1 discovery: locator: enabled: true # Dynamic route creation from registry lower-case-service-id: true ``` ### Response N/A (Configuration) ### Request Example ```bash # Access user service through gateway curl http://localhost:9201/user/1 # Response proxied from nacos-user-service: # {"data": {"id": 1, "username": "admin", "password": "123456"}, "code": 200} ``` ``` -------------------------------- ### Configure Spring Boot Admin Server and Client Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Configuration for Spring Boot Admin, including the server setup and client registration. The client needs to point to the admin server's URL and expose actuator endpoints. ```java @EnableAdminServer @SpringBootApplication public class AdminServerApplication { public static void main(String[] args) { SpringApplication.run(AdminServerApplication.class, args); } } ``` ```yaml # application.yml for admin-server server: port: 9301 spring: application: name: admin-server # application.yml for admin-client (any monitored service) server: port: 8206 spring: application: name: admin-client boot: admin: client: url: http://localhost:9301 # Admin server URL management: endpoints: web: exposure: include: '*' # Expose all actuator endpoints endpoint: health: show-details: always ``` -------------------------------- ### RestTemplate Configuration and Service Invocation (Java) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Configures RestTemplate for service-to-service calls with load balancing using Spring Cloud. It demonstrates making GET, POST requests and handling responses, including error scenarios. ```java @Configuration public class RestTemplateConfig { @Bean @LoadBalanced // Enable load balancing across service instances public RestTemplate restTemplate() { return new RestTemplate(); } } @RestController @RequestMapping("/user") public class RemoteUserController { @Autowired private RestTemplate restTemplate; @Value("${service-url.nacos-user-service}") private String userServiceUrl; @GetMapping("/{id}") public CommonResult getUser(@PathVariable Long id) { return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id); } @GetMapping("/getEntityByUsername") public CommonResult getEntityByUsername(@RequestParam String username) { ResponseEntity entity = restTemplate.getForEntity( userServiceUrl + "/user/getByUsername?username={1}", CommonResult.class, username); if (entity.getStatusCode().is2xxSuccessful()) { return entity.getBody(); } return new CommonResult("Operation failed", 500); } @PostMapping("/create") public CommonResult create(@RequestBody User user) { return restTemplate.postForObject(userServiceUrl + "/user/create", user, CommonResult.class); } } ``` -------------------------------- ### Access Service via NodePort Source: https://context7.com/macrozheng/springcloud-learning/llms.txt This snippet shows how to access a service exposed via NodePort in a Kubernetes cluster. It uses curl to send a GET request to the service's health endpoint. ```bash curl http://:30088/api/health ``` -------------------------------- ### Deploy and Verify Kubernetes Applications Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Bash commands to build and push a Docker image, then deploy the Kubernetes manifests (Deployment and Service). It also includes commands to verify the deployment status of pods and services. ```bash # Build and push Docker image mvn package -DskipTests docker build -t 192.168.3.102:5000/mall/mall-tiny-k8s:1.0-SNAPSHOT . docker push 192.168.3.102:5000/mall/mall-tiny-k8s:1.0-SNAPSHOT # Deploy to Kubernetes kubectl apply -f mall-tiny-k8s-deployment.yaml kubectl apply -f mall-tiny-k8s-service.yaml # Verify deployment kubectl get pods -l app=mall-tiny-k8s kubectl get services mall-tiny-k8s-service ``` -------------------------------- ### OpenFeign Declarative Service Client Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Demonstrates declarative HTTP client using OpenFeign for inter-service communication with fallback support. ```APIDOC ## UserService Feign Client ### Description Defines a Feign client interface for interacting with the user service, including fallback mechanisms for when the service is unavailable. ### Method N/A (Interface Definition) ### Endpoint N/A (Interface Definition) ### Parameters #### Feign Client Interface (`UserService`) - **value** (String) - The name of the target service (e.g., `nacos-user-service`). - **fallback** (Class) - The fallback implementation class to use when the target service is unavailable. #### Feign Client Methods - **create** (`@PostMapping("/user/create")`): Creates a new user. - **getUser** (`@GetMapping("/user/{id}")`): Retrieves a user by ID. - **getByUsername** (`@GetMapping("/user/getByUsername")`): Retrieves a user by username. - **update** (`@PostMapping("/user/update")`): Updates an existing user. - **delete** (`@PostMapping("/user/delete/{id}")`): Deletes a user by ID. ### Request Example (Calling the Feign Client) ```bash # Call a service that uses the UserService Feign client curl http://localhost:8308/user/1 ``` ### Response #### Success Response (from actual service) - **data** (Object) - Contains the user object if found. - **code** (Integer) - HTTP status code, expected to be 200. #### Response Example (from actual service) ```json { "data": { "id": 1, "username": "admin", "password": "123456" }, "code": 200 } ``` #### Fallback Response (when service unavailable) - **data** (Object) - Contains a default user object. - **id** (Long) - Default user ID (-1). - **username** (String) - Default username (`defaultUser`). - **password** (String) - Default password (`123456`). - **message** (String) - Indicates service unavailability. - **code** (Integer) - HTTP status code, typically 500. #### Fallback Response Example ```json { "data": { "id": -1, "username": "defaultUser", "password": "123456" }, "message": "Service unavailable", "code": 500 } ``` ``` -------------------------------- ### OpenFeign Declarative Service Client (Java) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Implements a declarative HTTP client using OpenFeign for inter-service communication. Includes a Feign client interface with fallback support and a controller that utilizes the Feign client. ```java // Feign client interface with fallback @FeignClient(value = "nacos-user-service", fallback = UserFallbackService.class) public interface UserService { @PostMapping("/user/create") CommonResult create(@RequestBody User user); @GetMapping("/user/{id}") CommonResult getUser(@PathVariable("id") Long id); @GetMapping("/user/getByUsername") CommonResult getByUsername(@RequestParam("username") String username); @PostMapping("/user/update") CommonResult update(@RequestBody User user); @PostMapping("/user/delete/{id}") CommonResult delete(@PathVariable("id") Long id); } // Fallback implementation for service unavailability @Component public class UserFallbackService implements UserService { @Override public CommonResult getUser(Long id) { User defaultUser = new User(-1L, "defaultUser", "123456"); return new CommonResult<>(defaultUser, "Service unavailable", 500); } // ... other fallback methods } // Controller using Feign client @RestController @RequestMapping("/user") public class UserFeignController { @Autowired private UserService userService; @GetMapping("/{id}") public CommonResult getUser(@PathVariable Long id) { return userService.getUser(id); } } ``` -------------------------------- ### Nacos Service Discovery Verification (Bash) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Demonstrates how to verify service registration with Nacos using curl. It shows the command to list instances for a given service name and the expected response format. ```bash # Start Nacos server first (single-node mode) sh startup.sh -m standalone # Verify service registration curl "http://localhost:8848/nacos/v1/ns/instance/list?serviceName=nacos-user-service" # Response shows registered instances: # {"name":"DEFAULT_GROUP@@nacos-user-service","hosts":[{"ip":"192.168.1.100","port":8206,"healthy":true}]} ``` -------------------------------- ### Accessing User Service via Gateway (Bash) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Demonstrates how to access the user service through the configured Spring Cloud Gateway. It shows a curl command to make a request and the expected proxied response from the Nacos-discovered user service. ```bash # Access user service through gateway curl http://localhost:9201/user/1 # Response proxied from nacos-user-service: # {"data": {"id": 1, "username": "admin", "password": "123456"}, "code": 200} ``` -------------------------------- ### Kubernetes Deployment Manifest for Microservice Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Kubernetes Deployment YAML defining how to deploy a microservice. It specifies the container image, ports, environment variables (like database connection strings), and volume mounts for logs. ```yaml # mall-tiny-k8s-deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: mall-tiny-k8s-deployment labels: app: mall-tiny-k8s spec: replicas: 1 selector: matchLabels: app: mall-tiny-k8s template: metadata: labels: app: mall-tiny-k8s spec: containers: - name: mall-tiny-k8s image: 192.168.3.102:5000/mall/mall-tiny-k8s:1.0-SNAPSHOT ports: - containerPort: 8088 env: - name: spring.datasource.url value: jdbc:mysql://mysql-service:3306/mall_tiny?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai - name: logging.path value: /var/logs volumeMounts: - mountPath: /var/logs name: log-volume volumes: - name: log-volume hostPath: path: /mydata/app/mall-tiny-k8s/logs type: DirectoryOrCreate ``` -------------------------------- ### Sentinel Rate Limiting Controller (Java) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt A Spring Boot REST controller demonstrating rate limiting using Alibaba Sentinel annotations. It includes methods for limiting by resource name, URL, and a custom block handler, along with a local exception handler. ```java @RestController @RequestMapping("/rateLimit") public class RateLimitController { // Rate limit by resource name with custom handler @GetMapping("/byResource") @SentinelResource(value = "byResource", blockHandler = "handleException") public CommonResult byResource() { return new CommonResult("Rate limited by resource name", 200); } // Rate limit by URL with default behavior @GetMapping("/byUrl") @SentinelResource(value = "byUrl", blockHandler = "handleException") public CommonResult byUrl() { return new CommonResult("Rate limited by URL", 200); } // Custom block handler class for reusable exception handling @GetMapping("/customBlockHandler") @SentinelResource( value = "customBlockHandler", blockHandler = "handleException", blockHandlerClass = CustomBlockHandler.class ) public CommonResult customBlockHandler() { return new CommonResult("Custom rate limiting", 200); } // Local block handler method public CommonResult handleException(BlockException exception) { return new CommonResult(exception.getClass().getCanonicalName(), 429); } } ``` -------------------------------- ### Spring Cloud Gateway Advanced Configuration with Nacos (YAML) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Advanced Spring Cloud Gateway configuration using Nacos for service discovery and Knife4j for API documentation. It sets up routes for user and order services, enabling dynamic route creation from the registry and stripping prefixes. ```yaml # Advanced gateway configuration with Nacos discovery and Knife4j spring: cloud: nacos: discovery: server-addr: localhost:8848 gateway: routes: - id: user-service uri: lb://micro-knife4j-user # Load-balanced URI predicates: - Path=/user-service/** filters: - StripPrefix=1 # Remove prefix before forwarding - id: order-service uri: lb://micro-knife4j-order predicates: - Path=/order-service/** filters: - StripPrefix=1 discovery: locator: enabled: true # Dynamic route creation from registry lower-case-service-id: true ``` -------------------------------- ### Seata Order Creation API Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Create an order, which triggers a distributed transaction managed by Seata. ```APIDOC ## POST /order/create ### Description Creates a new order and initiates a distributed transaction to deduct account balance and inventory. This operation is managed by Seata to ensure atomicity across microservices. ### Method POST ### Endpoint /order/create ### Parameters #### Query Parameters - **userId** (integer) - Required - The ID of the user placing the order. - **productId** (integer) - Required - The ID of the product being ordered. - **count** (integer) - Required - The quantity of the product. - **money** (integer) - Required - The total amount of the order. ### Request Example ```bash curl "http://localhost:8180/order/create?userId=1&productId=1&count=10&money=100" ``` ### Response #### Success Response (200) - **message** (string) - A success message indicating the order was created. - **code** (integer) - The HTTP status code, typically 200 for success. #### Failure Response (500) - **message** (string) - An error message indicating the reason for failure (e.g., insufficient balance). - **code** (integer) - The HTTP status code, typically 500 for failure. #### Response Example (Success) ```json {"message": "Order created successfully!", "code": 200} ``` #### Response Example (Failure) ```json {"message": "Insufficient balance", "code": 500} ``` ``` -------------------------------- ### Execute Seata Distributed Transaction Order Creation Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Bash command to trigger the order creation API endpoint, initiating a distributed transaction managed by Seata. The response indicates success (all services committed) or failure (all services rolled back). ```bash # Create order with distributed transaction curl "http://localhost:8180/order/create?userId=1&productId=1&count=10&money=100" # Response (success - all services committed): # {"message": "Order created successfully!", "code": 200} # Response (failure - all services rolled back): # {"message": "Insufficient balance", "code": 500} ``` -------------------------------- ### Spring Cloud Gateway Basic Route Configuration (YAML) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Configures a basic route for the gateway service, specifying the server port, user service URL, logging level, and application name. It defines a route with a path predicate that forwards requests to the user service. ```yaml # application.yml for gateway-service server: port: 9201 service-url: user-service: http://localhost:8206 logging: level: org.springframework.cloud.gateway: debug spring: application: name: gateway-service cloud: gateway: routes: - id: path_route # Route identifier uri: ${service-url.user-service}/user/{id} # Target URI predicates: # Route matching conditions - Path=/user/{id} ``` -------------------------------- ### Implement Seata Global Transaction Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Java code demonstrating Seata's global transaction management for microservices. It includes a controller and a service implementation using `@GlobalTransactional` to ensure atomicity across multiple services. ```java @RestController @RequestMapping(value = "/order") public class OrderController { @Autowired private OrderService orderService; @GetMapping("/create") public CommonResult create(Order order) { orderService.create(order); return new CommonResult("Order created successfully!", 200); } } // Service with global transaction @Service public class OrderServiceImpl implements OrderService { @GlobalTransactional(name = "create-order", rollbackFor = Exception.class) @Override public void create(Order order) { // 1. Create order record orderMapper.create(order); // 2. Deduct account balance (remote call) accountService.decrease(order.getUserId(), order.getMoney()); // 3. Deduct inventory (remote call) storageService.decrease(order.getProductId(), order.getCount()); // 4. Update order status orderMapper.update(order.getUserId(), 1); } } ``` -------------------------------- ### Invoke Service via Load-Balanced RestTemplate (Bash) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Demonstrates invoking a service that is load-balanced using RestTemplate. This curl command targets the local gateway port and expects a JSON response. ```bash # Invoke through load-balanced RestTemplate curl http://localhost:8308/user/1 # Response (load balanced across available instances): # {"data": {"id": 1, "username": "admin"}, "code": 200} ``` -------------------------------- ### Resilience4j Patterns Implementation (Java) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Demonstrates the use of Resilience4j annotations in a Spring Boot controller to implement circuit breaker, retry, rate limiter, and time limiter patterns. It includes a fallback method for retry failures and uses RestTemplate for external service calls. Dependencies include Spring Cloud CircuitBreaker and Resilience4j. ```java import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.client.RestTemplate; import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker; import io.github.resilience4j.retry.annotation.Retry; import io.github.resilience4j.ratelimiter.annotation.RateLimiter; import io.github.resilience4j.timelimiter.annotation.TimeLimiter; import java.util.concurrent.CompletableFuture; @RestController @RequestMapping("/breaker") public class CircleBreakerController { @Autowired private RestTemplate restTemplate; @Value("${service-url.user-service}") private String userServiceUrl; // Circuit breaker pattern @GetMapping("/circleBreakerApi/{id}") @CircuitBreaker(name = "circleBreakerApi") public CommonResult circleBreakerApi(@PathVariable Long id) { return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id); } // Retry pattern with fallback @GetMapping("/retryApi/{id}") @Retry(name = "retryApi", fallbackMethod = "fallbackAfterRetry") public CommonResult retryApi(@PathVariable Long id) { return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id); } // Rate limiter pattern @GetMapping("/rateLimiterApi/{id}") @RateLimiter(name = "rateLimiterApi") public CommonResult rateLimiterApi(@PathVariable Long id) { return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id); } // Time limiter pattern (async) @GetMapping("/timeLimiterApi/{id}") @TimeLimiter(name = "timeLimiterApi") public CompletableFuture timeLimiterApi(@PathVariable Long id) { return CompletableFuture.supplyAsync(this::callApiWithDelay); } // Fallback method for retry failures public CommonResult fallbackAfterRetry(Long id, Exception exception) { User defaultUser = new User(-1L, "defaultUser", "123456"); return new CommonResult<>(defaultUser, exception.getMessage(), 200); } private CommonResult callApiWithDelay() { // Simulate API call with delay try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, 1L); } } ``` -------------------------------- ### Access Spring Boot Admin Dashboard and Instances Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Commands to access the Spring Boot Admin dashboard and retrieve a list of registered application instances. The API response provides instance details including health status. ```bash # Access Admin dashboard open http://localhost:9301 # Check application health via Admin API curl http://localhost:9301/instances # Response: # [{"id":"abc123","name":"admin-client","health":{"status":"UP"}}] ``` -------------------------------- ### Access Eureka Dashboard and Services Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Commands to access the Eureka server dashboard and query registered services via its API. The response format is typically XML. ```bash # Access Eureka dashboard open http://localhost:8001 # Check registered services via API curl http://localhost:8001/eureka/apps # Response (XML): # # # NACOS-USER-SERVICE # # 192.168.1.100 # 8206 # UP # # # ``` -------------------------------- ### Nacos Service Discovery Configuration Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Configures a microservice to register with Nacos for service discovery, enabling service-to-service communication. ```APIDOC ## Nacos Service Registration ### Description This configuration allows a microservice to register itself with a Nacos server for service discovery. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters #### Application Configuration (application.yml) - **server.port** (Integer) - The port the microservice will run on. - **spring.application.name** (String) - The name of the microservice. - **spring.cloud.nacos.discovery.server-addr** (String) - The address of the Nacos server. ### Request Example ```yaml server: port: 8206 spring: application: name: nacos-user-service cloud: nacos: discovery: server-addr: localhost:8848 management: endpoints: web: exposure: include: '*' ``` ### Response #### Success Response (Verification) - **hosts** (Array) - A list of registered instances for the service. - **ip** (String) - The IP address of the registered instance. - **port** (Integer) - The port of the registered instance. - **healthy** (Boolean) - Indicates if the instance is healthy. #### Response Example (from `curl "http://localhost:8848/nacos/v1/ns/instance/list?serviceName=nacos-user-service"`) ```json { "name": "DEFAULT_GROUP@@nacos-user-service", "hosts": [ { "ip": "192.168.1.100", "port": 8206, "healthy": true } ] } ``` ``` -------------------------------- ### Eureka Server API Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Access the Eureka Server dashboard and check registered services via its API. ```APIDOC ## GET /eureka/apps ### Description Retrieves a list of all registered applications and their instances in the Eureka Server. ### Method GET ### Endpoint /eureka/apps ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **applications** (XML) - A complex XML structure containing information about registered applications and their instances. #### Response Example ```xml NACOS-USER-SERVICE 192.168.1.100 8206 UP ``` ``` -------------------------------- ### Nacos Service Discovery Configuration (YAML) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Configures a microservice to register with Nacos for service discovery. Specifies the server port, application name, and Nacos server address. ```yaml server: port: 8206 spring: application: name: nacos-user-service cloud: nacos: discovery: server-addr: localhost:8848 # Nacos server address management: endpoints: web: exposure: include: '*' ``` -------------------------------- ### Configure Eureka Server Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Configuration for an Eureka server to manage service registration and discovery. It specifies the server port and client settings to prevent self-registration and fetching the registry. ```yaml server: port: 8001 euroka: instance: hostname: localhost client: register-with-eureka: false # Don't register self fetch-registry: false # Don't fetch registry service-url: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ ``` -------------------------------- ### User Service API Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Core REST API for user management operations, demonstrating basic CRUD operations in a microservice architecture. ```APIDOC ## POST /user/create ### Description Creates a new user. ### Method POST ### Endpoint /user/create ### Parameters #### Request Body - **id** (Long) - Required - User's unique identifier. - **username** (String) - Required - User's login name. - **password** (String) - Required - User's password. ### Request Example ```json { "id": 1, "username": "admin", "password": "123456" } ``` ### Response #### Success Response (200) - **message** (String) - Confirmation message of the operation. - **code** (Integer) - HTTP status code, expected to be 200. #### Response Example ```json { "message": "Operation successful", "code": 200 } ``` ## GET /{id} ### Description Retrieves a user by their ID. ### Method GET ### Endpoint /user/{id} ### Parameters #### Path Parameters - **id** (Long) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **data** (Object) - Contains the user object if found. - **id** (Long) - User's unique identifier. - **username** (String) - User's login name. - **password** (String) - User's password. - **code** (Integer) - HTTP status code, expected to be 200. #### Response Example ```json { "data": { "id": 1, "username": "admin", "password": "123456" }, "code": 200 } ``` ## GET /getByUsername ### Description Retrieves a user by their username. ### Method GET ### Endpoint /user/getByUsername ### Parameters #### Query Parameters - **username** (String) - Required - The username to search for. ### Response #### Success Response (200) - **data** (Object) - Contains the user object if found. - **id** (Long) - User's unique identifier. - **username** (String) - User's login name. - **password** (String) - User's password. - **code** (Integer) - HTTP status code, expected to be 200. #### Response Example ```json { "data": { "id": 1, "username": "admin", "password": "123456" }, "code": 200 } ``` ``` -------------------------------- ### Sentinel Rate Limiting API Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Endpoints demonstrating Sentinel rate limiting by resource name, URL, and custom block handlers. ```APIDOC ## Sentinel Rate Limiting ### Description Implements rate limiting and flow control using Alibaba Sentinel annotations. ### Method GET ### Endpoint `/rateLimit/byResource` ### Parameters N/A ### Request Example ```java @RestController @RequestMapping("/rateLimit") public class RateLimitController { // Rate limit by resource name with custom handler @GetMapping("/byResource") @SentinelResource(value = "byResource", blockHandler = "handleException") public CommonResult byResource() { return new CommonResult("Rate limited by resource name", 200); } // Rate limit by URL with default behavior @GetMapping("/byUrl") @SentinelResource(value = "byUrl", blockHandler = "handleException") public CommonResult byUrl() { return new CommonResult("Rate limited by URL", 200); } // Custom block handler class for reusable exception handling @GetMapping("/customBlockHandler") @SentinelResource( value = "customBlockHandler", blockHandler = "handleException", blockHandlerClass = CustomBlockHandler.class ) public CommonResult customBlockHandler() { return new CommonResult("Custom rate limiting", 200); } // Local block handler method public CommonResult handleException(BlockException exception) { return new CommonResult(exception.getClass().getCanonicalName(), 429); } } ``` ### Response #### Success Response (200) - **message** (string) - Success message. - **code** (integer) - HTTP status code. #### Response Example ```json { "message": "Rate limited by resource name", "code": 200 } ``` ### Error Handling #### Error Response (429) - **message** (string) - Exception class name when rate limit is exceeded. - **code** (integer) - HTTP status code 429. #### Response Example ```json { "message": "com.alibaba.csp.sentinel.slots.block.flow.FlowException", "code": 429 } ``` ### Request Example ```bash # Normal request curl http://localhost:8401/rateLimit/byResource # After exceeding rate limit (configured in Sentinel dashboard) curl http://localhost:8401/rateLimit/byResource # Configure rate limiting rules via Sentinel dashboard or API curl -X POST http://localhost:8080/v1/flow/rules \ -H "Content-Type: application/json" \ -d '[{"resource":"byResource","grade":1,"count":5,"strategy":0,"controlBehavior":0}]' ``` ``` -------------------------------- ### Kubernetes Service Manifest for Microservice Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Kubernetes Service YAML to expose the microservice deployment. It defines the service type (NodePort), selector to match pods, and port mappings. ```yaml # mall-tiny-k8s-service.yaml apiVersion: v1 kind: Service metadata: name: mall-tiny-k8s-service spec: type: NodePort selector: app: mall-tiny-k8s ports: - port: 8088 targetPort: 8088 nodePort: 30088 ``` -------------------------------- ### OAuth2 Authorization Server Configuration (Java) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Configures Spring Authorization Server for OAuth2 authentication using JWT tokens. This Java code defines client registration, token settings, and customizes JWT claims to include authorities. It requires Spring Security and Spring Authorization Server dependencies. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.time.Duration; import java.util.UUID; import java.util.Set; import java.util.stream.Collectors; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.ImmutableJWKSet; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.oidc.OidcScopes; import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer; import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings; import org.springframework.security.oauth2.server.authorization.settings.ClientSettings; import org.springframework.security.oauth2.server.authorization.settings.TokenSettings; import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext; import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer; @Configuration @EnableWebSecurity @EnableMethodSecurity(jsr250Enabled = true, securedEnabled = true) public class AuthorizationServerConfig { @Bean public RegisteredClientRepository registeredClientRepository( JdbcTemplate jdbcTemplate, PasswordEncoder passwordEncoder) { RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId("messaging-client") .clientSecret(passwordEncoder.encode("123456")) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) .tokenSettings(TokenSettings.builder() .accessTokenTimeToLive(Duration.ofMinutes(60)) .refreshTokenTimeToLive(Duration.ofHours(24)) .build()) .redirectUri("http://127.0.0.1:9401/login/oauth2/code/messaging-client-oidc") .scope(OidcScopes.OPENID) .scope(OidcScopes.PROFILE) .scope("message.read") .scope("message.write") .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()) .build(); JdbcRegisteredClientRepository repository = new JdbcRegisteredClientRepository(jdbcTemplate); if (repository.findByClientId(registeredClient.getClientId()) == null) { repository.save(registeredClient); } return repository; } @Bean public OAuth2TokenCustomizer oAuth2TokenCustomizer() { return context -> { if (context.getPrincipal().getPrincipal() instanceof UserDetails user) { Set scopes = context.getAuthorizedScopes(); Set authorities = user.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toSet()); authorities.addAll(scopes); context.getClaims().claim("authorities", authorities); } }; } @Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings.builder() .issuer("http://192.168.3.48:9401") .build(); } } ``` -------------------------------- ### User Service API (Java) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Defines the core REST API for user management operations, including user domain model and controller endpoints for CRUD operations. It uses Spring Boot annotations for request mapping and data binding. ```java public class User { private Long id; private String username; private String password; // getters and setters } @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/create") public CommonResult create(@RequestBody User user) { userService.create(user); return new CommonResult("Operation successful", 200); } @GetMapping("/{id}") public CommonResult getUser(@PathVariable Long id) { User user = userService.getUser(id); return new CommonResult<>(user); } } ``` -------------------------------- ### Spring Boot Admin API Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Access the Spring Boot Admin dashboard and check application health via its API. ```APIDOC ## GET /instances ### Description Retrieves a list of all registered Spring Boot Admin clients and their health status. ### Method GET ### Endpoint /instances ### Parameters #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **instances** (Array of Objects) - A list of registered applications, each with an id, name, and health status. - **id** (string) - The unique identifier of the application instance. - **name** (string) - The name of the application. - **health** (object) - An object containing the health status. - **status** (string) - The health status (e.g., "UP", "DOWN"). #### Response Example ```json [{"id":"abc123","name":"admin-client","health":{"status":"UP"}}] ``` ``` -------------------------------- ### RestTemplate Configuration (YAML) Source: https://context7.com/macrozheng/springcloud-learning/llms.txt Defines the service URL for load balancing in the application's YAML configuration. This property is used by RestTemplate to locate and communicate with the target service. ```yaml # application.yml service-url: nacos-user-service: http://nacos-user-service # Service name for load balancing ``` -------------------------------- ### Cancel Consent Action - JavaScript Source: https://github.com/macrozheng/springcloud-learning/blob/master/micro-sas/sas-authorization-server/src/main/resources/templates/consent.html This JavaScript function, `cancelConsent`, is responsible for resetting the consent form and submitting it when the user chooses to cancel. It is typically used on a custom consent page to handle user rejection of app permissions. ```javascript function cancelConsent() { document.consent_form.reset(); document.consent_form.submit(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.