Flat Preloader Icon

Microservices Interview Programs

1. Write a Java code snippet to create a simple microservice using Spring Boot.
				
					@RestController
public class GreetingController {
    @GetMapping("/greet")
    public String greet() {
        return "Hello from the microservice!";
    }
}

				
			
2. Explain how you would implement inter-service communication in a microservices architecture.
Implementing inter-service communication can be done using technologies like RESTful APIs, gRPC, or message queues (e.g., RabbitMQ, Kafka). Here’s a code snippet for a simple RESTful communication in Java using Spring Cloud Feign:
				
					@FeignClient(name = "other-service")
public interface OtherServiceClient {
    @GetMapping("/other-service/endpoint")
    String getFromOtherService();
}

				
			
3. Write code to demonstrate the use of a circuit breaker pattern (e.g., Hystrix) in microservices for handling failures.
				
					@RestController
public class CircuitBreakerController {
    @GetMapping("/fallback")
    @HystrixCommand(fallbackMethod =
    "fallbackMethod")
    public String serviceWithCircuitBreaker() {
        // Your microservice logic that might fail
    }

    public String fallbackMethod() {
        return
        "Fallback response 
        when the service is down";
    }
}

				
			
In this example, the @HystrixCommand annotation applies a circuit breaker to the “serviceWithCircuitBreaker” method, and if it fails, it falls back to the “fallbackMethod.”
4. Explain how you would implement centralized logging and monitoring in a microservices architecture.
				
					@RestController
public class LoggingController {
    private Logger logger =
    LoggerFactory.getLogger
    (LoggingController.class);

    @GetMapping("/log")
    public String logExample() {
        logger.info
        ("This is a log message.");
        return "Logged a message!";
    }
}

				
			
5. Write code to demonstrate the implementation of API Gateway in a microservices architecture using Spring Cloud Gateway.
				
					@SpringBootApplication
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run
        (ApiGatewayApplication.class, args);
    }

    @Bean
    public RouteLocator customRouteLocator
    (RouteLocatorBuilder builder) {
        return builder.routes()
            .route("service-route", r -> r
                .path("/service/**")
                .uri
                ("http://service-microservice")
            )
            .build();
    }
}

				
			
6. Implement a simple RESTful microservice in Java using Spring Boot.
				
					@RestController
@RequestMapping("/api")
public class GreetingController {

    @GetMapping("/greeting")
    public String greeting() {
        return 
        "Hello from the microservice!";
    }
}

				
			
7. Develop a microservice in Java that interacts with a database.
				
					@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
}

				
			
8. Implement caching in a Java microservice.
				
					@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Cacheable("users")
    public User getUserById(Long id) {
        return userRepository.findById(id);
    }
}

				
			
9. How do you implement logging and monitoring in Java-based microservices?
				
					import org.apache.log4j.Logger;

public class LoggingExample {
    final static Logger 
    logger = Logger.getLogger
    (LoggingExample.class);

    public static void main(String[] args) {
        logger.debug("Debug message");
        logger.info("Info message");
        logger.warn("Warn message");
        logger.error("Error message");
        logger.fatal("Fatal message");
    }
}

				
			
10. Implement security measures in a Java microservice.
				
					@Configuration
@EnableWebSecurity
public class SecurityConfig extends
WebSecurityConfigurerAdapter {

    @Override
    protected void configure
    (HttpSecurity http) 
    throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/secure/**")
                .authenticated()
                .anyRequest().permitAll()
                .and()
            .formLogin();
    }
}