Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eureka + Gateway #97

Open
wants to merge 1 commit into
base: lab6
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,24 @@
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

import java.io.IOException;

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServer {

private static Logger logger = LoggerFactory.getLogger(DiscoveryServer.class);

public static void main(String... args) throws IOException {
// Look for configuration in discovery-server.properties or discovery-server.yml
System.setProperty("spring.config.name", "discovery-server");

var ctx = SpringApplication.run(DiscoveryServer.class, args);
assert (ctx != null);
logger.info("Started ...");
System.in.read();
ctx.close();
}
private static Logger logger = LoggerFactory.getLogger(DiscoveryServer.class);
public static void main(String... args) throws IOException {
// Look for configuration in discovery-server.properties or discovery-server.yml
System.setProperty("spring.config.name", "discovery-server");
var ctx = SpringApplication.run(DiscoveryServer.class, args);
assert (ctx != null);
logger.info("Started ...");
System.in.read();
ctx.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ spring:
name: discovery-service
# Configure this Discovery Server
#TODO here you add configurations for server
server:
port: 3000

eureka:
client:
register-with-eureka: false
fetch-registry: false

logging:
pattern:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,77 +1,101 @@
package com.eureka.persons;

import com.eureka.persons.ex.NotFoundException;
import com.eureka.persons.person.Person;
import com.eureka.persons.services.PersonService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/persons")
public class PersonsController {
private PersonService personService;

public PersonsController(PersonService personService) {
this.personService = personService;
}

/**
* Handles requests to list all persons.
*/
//TODO find all persons using the functions already implemented and sort them by id
@ResponseStatus(HttpStatus.OK)
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<Person> list() {
return new ArrayList<>();
}

/**
* Handles requests to create a person.
*/
//TODO save a person to the db or throw PersonsException
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public void create(@RequestBody Person person, BindingResult result) {
}

/**
* Returns the {@code Person} instance with id {@code id}
*
* @param id
* @return
*/
//TODO find a person by id or throw NotFoundException
@ResponseStatus(HttpStatus.OK)
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Person show(@PathVariable Long id) {
return new Person();
}

/**
* Updates the {@code Person} instance with id {@code id}
*
* @param updatedPerson
* @param id
* @return
*/
//TODO update an existing person if found else throw NotFoundException
@ResponseStatus(HttpStatus.NO_CONTENT)
@PutMapping("/{id}")
public void update(@RequestBody Person updatedPerson, @PathVariable Long id) {
}

/**
* Delete the {@code Person} instance with id {@code id}
*
* @param id
*/
//TODO delete a person
@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
}
private PersonService personService;

public PersonsController(PersonService personService) {
this.personService = personService;
}

/**
* Handles requests to list all persons.
*/
//TODO find all persons using the functions already implemented and sort them by id
@ResponseStatus(HttpStatus.OK)
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<Person> list() {
return personService
.findAll().stream()
.sorted(Comparator.comparing(Person::getId))
.collect(Collectors.toList());
}

/**
* Handles requests to create a person.
*/
//TODO save a person to the db or throw PersonsException
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public void create(@RequestBody Person person, BindingResult result) {
if (result.hasErrors())
throw new PersonsException(HttpStatus.BAD_REQUEST, "Person couldn't be added!");

personService.save(person);
}

/**
* Returns the {@code Person} instance with id {@code id}
*
* @param id
* @return
*/
//TODO find a person by id or throw NotFoundException
@ResponseStatus(HttpStatus.OK)
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Person show(@PathVariable Long id) {
var personIdQuery = personService.findById(id);
if (personIdQuery.isEmpty())
throw new NotFoundException(Person.class, id);

return personIdQuery.get();
}

/**
* Updates the {@code Person} instance with id {@code id}
*
* @param updatedPerson
* @param id
* @return
*/
//TODO update an existing person if found else throw NotFoundException
@ResponseStatus(HttpStatus.NO_CONTENT)
@PutMapping("/{id}")
public void update(@RequestBody Person updatedPerson, @PathVariable Long id) {
var personIdQuery = personService.findById(id);

personIdQuery.ifPresent(person -> person = updatedPerson);
// else
throw new NotFoundException(Person.class, id);
}

/**
* Delete the {@code Person} instance with id {@code id}
*
* @param id
*/
//TODO delete a person
@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
var personIdQuery = personService.findById(id);
if (personIdQuery.isEmpty())
throw new NotFoundException(Person.class, id);

personService.delete(personIdQuery.get());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,25 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

import java.io.IOException;

@EntityScan(basePackages = "com.eureka.persons")
@SpringBootApplication
@EnableEurekaClient
public class PersonsServer {

private static Logger logger = LoggerFactory.getLogger(PersonsServer.class);

public static void main(String... args) throws IOException {
// Look for configuration in persons-server.properties or persons-server.yml
System.setProperty("spring.config.name", "persons-server");

var ctx = SpringApplication.run(PersonsServer.class, args);
assert (ctx != null);
logger.info("Started ...");
System.in.read();
ctx.close();
}
private static final Logger logger = LoggerFactory.getLogger(PersonsServer.class);
public static void main(String... args) throws IOException {
// Look for configuration in persons-server.properties or persons-server.yml
System.setProperty("spring.config.name", "persons-server");
var ctx = SpringApplication.run(PersonsServer.class, args);
assert (ctx != null);
logger.info("Started ...");
System.in.read();
ctx.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
@Service
@Transactional
public class PersonServiceImpl implements PersonService {
private PersonRepo personRepo;
private final PersonRepo personRepo;

public PersonServiceImpl(PersonRepo personRepo) {
this.personRepo = personRepo;
Expand Down
6 changes: 6 additions & 0 deletions eureka/persons-server/src/main/resources/persons-server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ server:

# Discovery Server Access
#TODO here you add configurations for eureka client
eureka:
client:
service-url:
defaultZone: http://localhost:3000/eureka
fetch-registry: true
register-with-eureka: true

info:
app:
Expand Down
18 changes: 7 additions & 11 deletions lab-6-api-gateway/api-gateway-project/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.5</version>
<relativePath/> <!-- lookup parent from repository -->
<artifactId>lab-6-api-gateway</artifactId>
<groupId>com.example</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.example</groupId>
<artifactId>api-gateway-project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-gateway-project</name>
Expand All @@ -18,7 +16,6 @@
<spring-cloud.version>2021.0.1</spring-cloud.version>
</properties>


<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -33,16 +30,15 @@
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
public class ApiGatewayProjectApplication {

public static void main(String[] args) {
SpringApplication.run(ApiGatewayProjectApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
spring.main.web-application-type=reactive
Original file line number Diff line number Diff line change
@@ -1,6 +1,33 @@
server:
port: 8080

#TODO use eureka to discover the URL for the service1 and service2
#TODO configure spring cloud gateway to route the request to downstream services (service1 and service2) based on the paths(/api/greeting, /product)
#TODO for greeting endpoint add a route to accept requests to /greeting but before calling service1 it must append api before the greeting path (HINT: rewrite path filter)
#and method types (GET,POST)
#and method types (GET,POST)
spring:
application:
name: gateway
cloud:
gateway:
routes:
- id: service1
uri: http://localhost:8081
predicates:
- Path=/greeting/**
filters:
- RewritePath=/greeting, /api/greeting/
- id: service2
uri: http://localhost:8082
predicates:
- Path=/product/**
- id: persons
uri: http://localhost:4001
predicates:
- Path=/persons/**
eureka:
client:
service-url:
defaultZone: http://localhost:3000/eureka
fetch-registry: true
register-with-eureka: true
5 changes: 5 additions & 0 deletions lab-6-api-gateway/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
<module>service2</module>
</modules>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
Expand Down
Loading