36
loading...
This website collects cookies to deliver better user experience
@FeignClient(name = "cepClient", url = "${externalUrl}")
public interface CepClient {
@GetMapping(value = "/v1/cep/{cep}")
Cep get(@PathVariable("cep") String cep);
}
@Data
public class Cep {
private String logradouro;
private String bairro;
private String cidade;
private String estado;
}
@Configuration
@EnableAsync
public class ThreadPoolTaskAsyncConfig {
@Bean(name = "threadPoolTaskAsyncExecutor")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setMaxPoolSize(50);
threadPoolTaskExecutor.setCorePoolSize(50);
threadPoolTaskExecutor.setQueueCapacity(50);
return threadPoolTaskExecutor;
}
}
@Slf4j
@Component
@NoArgsConstructor
public class CustomRetryer implements Retryer {
@Value("${retryMaxAttempt}")
private int retryMaxAttempt;
@Value("${retryInterval}")
private long retryInterval;
private int attempt = 1;
public CustomRetryer(int retryMaxAttempt, Long retryInterval) {
this.retryMaxAttempt = retryMaxAttempt;
this.retryInterval = retryInterval;
}
@Override
public void continueOrPropagate(RetryableException e) {
log.info("Feign retry attempt {} due to {} ", attempt, e.getMessage());
if(attempt++ == retryMaxAttempt){
throw e;
}
try {
Thread.sleep(retryInterval);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
}
@Override
public Retryer clone() {
return new CustomRetryer(retryMaxAttempt, retryInterval);
}
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import java.util.Optional;
@SpringBootApplication
@EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Service
public class ConsultService {
@Autowired
private CepClient client;
public Optional<Cep> consultCep(String cep){
try {
Cep cepResponse = this.getByCep(cep).get();
return Optional.of(cepResponse);
}catch (RetryableException | InterruptedException | ExecutionException e){
//TODO
}
return Optional.empty();
}
@Async("threadPoolTaskAsyncExecutor")
public CompletableFuture<Cep> getByCep(String cep){
return CompletableFuture.completedFuture(client.get(cep));
}
}
package com.example.demo.config;
import com.example.demo.service.ScheduleService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
@ComponentScan(basePackages = "com.example.demo.service", basePackageClasses = {ScheduleService.class})
public class ThreadPoolTaskSchedulerConfig {
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(5);
threadPoolTaskScheduler.setThreadNamePrefix("ScheduleService");
return threadPoolTaskScheduler;
}
}
@Data
@Entity
@NoArgsConstructor
public class Response {
@Id
private String cep;
private Date create_at;
private Date update_at;
private String logradouro;
private String bairro;
private String cidade;
private String estado;
private boolean success;
}
@Repository
public interface ResponseRepository extends JpaRepository<Response, Integer> {
Optional<List<Response>> findAllBySuccessIsFalse();
Optional<Response> findByCep(String cep);
}
@Component("scheduleService")
public class ScheduleService {
@Value("${cronTimer.reprocess}")
private String reprocess;
@Autowired
private ThreadPoolTaskScheduler taskScheduler;
@Autowired
private ResponseRepository repository;
@Autowired
private ConsultService consultService;
@PostConstruct
public void init() {
taskScheduler.schedule(() -> {
repository.findAllBySuccessIsFalse().ifPresent(cepList -> cepList.forEach(cep -> consultService.consultCep(cep.getCep())));
}, new CronTrigger(reprocess));
}
}
0 */1 * * * *
(Para saber mais sobre Cron Expressions)false
e vai chamar a nossa service. Para finalizar a nossa única alteração será na nossa service onde vamos começar a salvar os registros das nossas requisições e no campo success definimos se foi sucesso true
ou falha false
:@Service
public class ConsultService {
@Autowired
private CepClient client;
@Autowired
private ResponseRepository repository;
public Optional<Cep> consultCep(String cep){
try {
Cep cepResponse = this.getByCep(cep).get();
Response response = new Response();
response.setCep(cep);
response.setCreate_at(new Date());
response.setLogradouro(cepResponse.getLogradouro());
response.setBairro(cepResponse.getBairro());
response.setCidade(cepResponse.getCidade());
response.setEstado(cepResponse.getEstado());
repository.save(response);
return Optional.of(cepResponse);
}catch (RetryableException | InterruptedException | ExecutionException e){
Optional<Response> repositoryById = repository.findByCep(cep);
Response response;
if(repositoryById.isPresent()){
response = repositoryById.get();
response.setUpdate_at(new Date());
}else {
response = new Response();
response.setCep(cep);
response.setCreate_at(new Date());
}
repository.save(response);
}
return Optional.empty();
}
@Async("threadPoolTaskAsyncExecutor")
public CompletableFuture<Cep> getByCep(String cep){
return CompletableFuture.completedFuture(client.get(cep));
}
}
@SpringBootApplication
@EnableFeignClients
@EnableScheduling
public class DemoApplication implements CommandLineRunner {
@Autowired
private ConsultService service;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Optional<Cep> cep = service.consultCep("01032000");
cep.ifPresent(System.out::println);
}
}