- Beranda
- Komunitas
- Tech
- Programmer Forum
[Java Spring Boot Multi Threading]
TS
sangawan
[Java Spring Boot Multi Threading]
Permisi gan ane mau tanya cara multithreading ini Rest Api disemua action gmn caranya ya?Berikut adalah kode awal sebelum percobaan multithreading terdiri dari CurrencysController,CurrencyRepository .
Kode Berikut adalah sudah terjadi percobaan multithreading pada @GetMapping("/currencys") dan penambahan currencyservice.java dan AsyncConfiguration .java.
Dengan dilakukan Debugging pada font yang sudah saya beri warna merah. hasil currencys berupa null, yang mana pada code sebelumnya datanya ada.
Quote:
//Mata Uang
@RestController
@RequestMapping(SpringDataJPAMultitenantConstants.TENANT_MASTER)
public class CurrencyController {
private static final Logger LOGGER = LoggerFactory.getLogger(CurrencyController.class);
@Autowired
CurrencyRepository currencyRepository;
@Autowired
GlAccntRepository glaccntRepository;
@Autowired
NewNumberService newNumberService;
// @PostMapping("/saveCurrencys")
// @Async("taskExecutor")
@PostMapping("/currencys")
@PreAuthorize("hasRole('USER')")
@Transactional
public ResponseEntity<?> createCurrencys(@Valid @RequestBody PCurrency pcurrency) {
// Currencys currencys = new Currencys(pcurrency.getCurrencyname(), pcurrency.getExchangerate());
Currencys checkcurrency = currencyRepository.findBycurrencynameid(pcurrency.getCurrencyname(), pcurrency.getCurrencyid());
if (!(checkcurrency == null)) {
throw new ConflictException("Mata Uang " + checkcurrency.getCurrencyname() + " sudah ada.");
}
Currencys currencys = new Currencys();
BigDecimal BigDec1 = new BigDecimal("0");
currencys.setCurrencyname(pcurrency.getCurrencyname());
currencys.setExchangerate(pcurrency.getExchangerate());
currencys.setCurrencysymbol("");
currencys.setTranslationrate(BigDec1);
currencyRepository.save(currencys);
Currencys currencys1 = currencyRepository.findByCurrencyname(pcurrency.getCurrencyname());
if (pcurrency.isAutodefaccnt()) {
newNumberService.callCreateDefaccnt(currencys1.getCurrencyid());
}
List<Currencys> lcurrencys = currencyRepository.findAll();
return new ResponseEntity(new ListResponse(true, lcurrencys),
HttpStatus.OK);
}
@GetMapping("/currencys")
@GetMapping("/currencys")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> findAll() {
List<Currencys> currencys = currencyRepository.findAll();
if (currencys == null || currencys.isEmpty()) {
throw new NoContentException("Tidak ada data Mata Uang");
}
return new ResponseEntity(new ListResponse(true, currencys),
HttpStatus.OK);
}
// @GetMapping("/currencys/{id}")
// @Async("taskExecutor")
@GetMapping("/currencys/{id}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> getCurrencysById(@PathVariable("id") int id){
// return new ResponseEntity<Currencys>(currencyRepository.findBycurrencyid(id), HttpStatus.OK);
Currencys currencys = currencyRepository.findBycurrencyid(id);
if (currencys == null) {
throw new NotFound("ID Mata Uang " + id + " tidak ada.");
}
return new ResponseEntity(new SingleResponse(true, currencys),
HttpStatus.OK);
// return currencys;
}
// @DeleteMapping("/deleteCurrencys/{id}")
// @Async("taskExecutor")
@DeleteMapping("/currencys/{id}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> deleteCurrencys(@PathVariable("id") List<Integer> ids) throws SQLException {
for (int id : ids) {
if (id != 1) {
Currencys currencys = currencyRepository.findBycurrencyid(id);
if (currencys == null) {
throw new NotFound("ID Mata Uang " + id + " tidak ada.");
}
try {
currencyRepository.deleteById(id);
} catch (DataIntegrityViolationException ex) {
if (ex.getCause() instanceof ConstraintViolationException) {
throw new ConflictException("Tidak dapat menghapus Mata Uang " + currencys.getCurrencyname());
}
}
}
}
List<Currencys> lcurrencys = currencyRepository.findAll();
return new ResponseEntity(new ListResponse(true, lcurrencys),
HttpStatus.OK);
}
// @Async("taskExecutor")
@PutMapping("/currencys")
@PreAuthorize("hasRole('USER')")
@Transactional
public ResponseEntity<?> updateCurrencys(@Valid @RequestBody PCurrency pcurrency) {
Currencys currencys = currencyRepository.findBycurrencyid(pcurrency.getCurrencyid());
if (currencys == null) {
throw new DatasourceNotFoundException("Mata Uang " + pcurrency.getCurrencyid() + " tidak ada.");
}
// Currencys checkcurrencys = currencyRepository.findByCurrencyname(pcurrency.getCurrencyname());
Currencys checkcurrencys = currencyRepository.findBycurrencyid(pcurrency.getCurrencyid());
if (checkcurrencys.getCurrencyid() == pcurrency.getCurrencyid()) {
currencys.setCurrencyname(pcurrency.getCurrencyname());
currencys.setExchangerate(pcurrency.getExchangerate());
currencyRepository.save(currencys);
newNumberService.callCreateDefaccnt(pcurrency.getCurrencyid());
List<Currencys> lcurrencys = currencyRepository.findAll();
return new ResponseEntity(new ListResponse(true, lcurrencys),
HttpStatus.OK);
} else {
throw new ConflictException("Mata Uang " + pcurrency.getCurrencyname() + " sudah ada.");
}
}
}
@RestController
@RequestMapping(SpringDataJPAMultitenantConstants.TENANT_MASTER)
public class CurrencyController {
private static final Logger LOGGER = LoggerFactory.getLogger(CurrencyController.class);
@Autowired
CurrencyRepository currencyRepository;
@Autowired
GlAccntRepository glaccntRepository;
@Autowired
NewNumberService newNumberService;
// @PostMapping("/saveCurrencys")
// @Async("taskExecutor")
@PostMapping("/currencys")
@PreAuthorize("hasRole('USER')")
@Transactional
public ResponseEntity<?> createCurrencys(@Valid @RequestBody PCurrency pcurrency) {
// Currencys currencys = new Currencys(pcurrency.getCurrencyname(), pcurrency.getExchangerate());
Currencys checkcurrency = currencyRepository.findBycurrencynameid(pcurrency.getCurrencyname(), pcurrency.getCurrencyid());
if (!(checkcurrency == null)) {
throw new ConflictException("Mata Uang " + checkcurrency.getCurrencyname() + " sudah ada.");
}
Currencys currencys = new Currencys();
BigDecimal BigDec1 = new BigDecimal("0");
currencys.setCurrencyname(pcurrency.getCurrencyname());
currencys.setExchangerate(pcurrency.getExchangerate());
currencys.setCurrencysymbol("");
currencys.setTranslationrate(BigDec1);
currencyRepository.save(currencys);
Currencys currencys1 = currencyRepository.findByCurrencyname(pcurrency.getCurrencyname());
if (pcurrency.isAutodefaccnt()) {
newNumberService.callCreateDefaccnt(currencys1.getCurrencyid());
}
List<Currencys> lcurrencys = currencyRepository.findAll();
return new ResponseEntity(new ListResponse(true, lcurrencys),
HttpStatus.OK);
}
@GetMapping("/currencys")
@GetMapping("/currencys")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> findAll() {
List<Currencys> currencys = currencyRepository.findAll();
if (currencys == null || currencys.isEmpty()) {
throw new NoContentException("Tidak ada data Mata Uang");
}
return new ResponseEntity(new ListResponse(true, currencys),
HttpStatus.OK);
}
// @GetMapping("/currencys/{id}")
// @Async("taskExecutor")
@GetMapping("/currencys/{id}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> getCurrencysById(@PathVariable("id") int id){
// return new ResponseEntity<Currencys>(currencyRepository.findBycurrencyid(id), HttpStatus.OK);
Currencys currencys = currencyRepository.findBycurrencyid(id);
if (currencys == null) {
throw new NotFound("ID Mata Uang " + id + " tidak ada.");
}
return new ResponseEntity(new SingleResponse(true, currencys),
HttpStatus.OK);
// return currencys;
}
// @DeleteMapping("/deleteCurrencys/{id}")
// @Async("taskExecutor")
@DeleteMapping("/currencys/{id}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> deleteCurrencys(@PathVariable("id") List<Integer> ids) throws SQLException {
for (int id : ids) {
if (id != 1) {
Currencys currencys = currencyRepository.findBycurrencyid(id);
if (currencys == null) {
throw new NotFound("ID Mata Uang " + id + " tidak ada.");
}
try {
currencyRepository.deleteById(id);
} catch (DataIntegrityViolationException ex) {
if (ex.getCause() instanceof ConstraintViolationException) {
throw new ConflictException("Tidak dapat menghapus Mata Uang " + currencys.getCurrencyname());
}
}
}
}
List<Currencys> lcurrencys = currencyRepository.findAll();
return new ResponseEntity(new ListResponse(true, lcurrencys),
HttpStatus.OK);
}
// @Async("taskExecutor")
@PutMapping("/currencys")
@PreAuthorize("hasRole('USER')")
@Transactional
public ResponseEntity<?> updateCurrencys(@Valid @RequestBody PCurrency pcurrency) {
Currencys currencys = currencyRepository.findBycurrencyid(pcurrency.getCurrencyid());
if (currencys == null) {
throw new DatasourceNotFoundException("Mata Uang " + pcurrency.getCurrencyid() + " tidak ada.");
}
// Currencys checkcurrencys = currencyRepository.findByCurrencyname(pcurrency.getCurrencyname());
Currencys checkcurrencys = currencyRepository.findBycurrencyid(pcurrency.getCurrencyid());
if (checkcurrencys.getCurrencyid() == pcurrency.getCurrencyid()) {
currencys.setCurrencyname(pcurrency.getCurrencyname());
currencys.setExchangerate(pcurrency.getExchangerate());
currencyRepository.save(currencys);
newNumberService.callCreateDefaccnt(pcurrency.getCurrencyid());
List<Currencys> lcurrencys = currencyRepository.findAll();
return new ResponseEntity(new ListResponse(true, lcurrencys),
HttpStatus.OK);
} else {
throw new ConflictException("Mata Uang " + pcurrency.getCurrencyname() + " sudah ada.");
}
}
}
Quote:
public interface CurrencyRepository extends JpaRepository<Currencys, Integer> {
Currencys findBycurrencyid(int id);
@Query("SELECT v FROM Currencys v where v.currencyname = :currencyname")
Currencys findByCurrencyname(@Param("currencyname") String currencyname);
@Query("SELECT v FROM Currencys v where v.currencyname = :currencyname and v.currencyid <> :currencyid")
Currencys findBycurrencynameid(@Param("currencyname") String currencyname, @Param("currencyid") int currencyid);
@Query(value = "select * from CURRENCYS", nativeQuery = true)
List<Currencys> findAllCurr();
}
Currencys findBycurrencyid(int id);
@Query("SELECT v FROM Currencys v where v.currencyname = :currencyname")
Currencys findByCurrencyname(@Param("currencyname") String currencyname);
@Query("SELECT v FROM Currencys v where v.currencyname = :currencyname and v.currencyid <> :currencyid")
Currencys findBycurrencynameid(@Param("currencyname") String currencyname, @Param("currencyid") int currencyid);
@Query(value = "select * from CURRENCYS", nativeQuery = true)
List<Currencys> findAllCurr();
}
Kode Berikut adalah sudah terjadi percobaan multithreading pada @GetMapping("/currencys") dan penambahan currencyservice.java dan AsyncConfiguration .java.
Quote:
// @GetMapping("/currencys")
@Async("taskExecutor")
/*@GetMapping("/currencys")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> findAll() {
List<Currencys> currencys = currencyRepository.findAll();
// if (currencys == null || currencys.isEmpty()) {
// throw new NoContentException("Tidak ada data Mata Uang");
// }
return new ResponseEntity(new ListResponse(true, currencys),
HttpStatus.OK);
}*/
// @GetMapping("/currencys")
// @PreAuthorize("hasRole('USER')")
// public CompletableFuture<?> findAllUsers() {
// return service.findAllUsers().thenApply(ResponseEntity:
k);
// }
@GetMapping("/currencys")
@PreAuthorize("hasRole('USER')")
public CompletableFuture<ResponseEntity> getAllCurrency() throws Exception{
return service.findAllUsers().<ResponseEntity>thenApply(ResponseEntity:
k)
.exceptionally(handleGetCarFailure);
}
private static Function<Throwable, ResponseEntity<? extends List<Currencys>>> handleGetCarFailure = throwable -> {
LOGGER.error("Failed to read records: {}", throwable);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
};
@Async("taskExecutor")
/*@GetMapping("/currencys")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> findAll() {
List<Currencys> currencys = currencyRepository.findAll();
// if (currencys == null || currencys.isEmpty()) {
// throw new NoContentException("Tidak ada data Mata Uang");
// }
return new ResponseEntity(new ListResponse(true, currencys),
HttpStatus.OK);
}*/
// @GetMapping("/currencys")
// @PreAuthorize("hasRole('USER')")
// public CompletableFuture<?> findAllUsers() {
// return service.findAllUsers().thenApply(ResponseEntity:
k);// }
@GetMapping("/currencys")
@PreAuthorize("hasRole('USER')")
public CompletableFuture<ResponseEntity> getAllCurrency() throws Exception{
return service.findAllUsers().<ResponseEntity>thenApply(ResponseEntity:
k).exceptionally(handleGetCarFailure);
}
private static Function<Throwable, ResponseEntity<? extends List<Currencys>>> handleGetCarFailure = throwable -> {
LOGGER.error("Failed to read records: {}", throwable);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
};
Quote:
@Configuration
@EnableAsync(proxyTargetClass=true)
public class AsyncConfiguration implements AsyncConfigurer {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncConfiguration.class);
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
LOGGER.debug("Creating Async Task Executor");
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("Thread-");
executor.initialize();
return executor;
}
@Override
public Executor getAsyncExecutor() {
return taskExecutor();
}
}
@EnableAsync(proxyTargetClass=true)
public class AsyncConfiguration implements AsyncConfigurer {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncConfiguration.class);
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
LOGGER.debug("Creating Async Task Executor");
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("Thread-");
executor.initialize();
return executor;
}
@Override
public Executor getAsyncExecutor() {
return taskExecutor();
}
}
Quote:
@Service
public class CurrencysService {
@Autowired
private CurrencyRepository repository;
Object target;
Logger logger = LoggerFactory.getLogger(CurrencysService.class);
@Async("taskExecutor")
public CompletableFuture<List<Currencys>> findAllUsers() throws InterruptedException{
LOGGER.info("Request to get a list of cars");
List<Currencys> currencys = repository.findAll();
if (currencys == null || currencys.isEmpty()) {
throw new NoContentException("Tidak ada data Mata Uang");
}
Thread.sleep(1000L);
return CompletableFuture.completedFuture(currencys);
}
}
public class CurrencysService {
@Autowired
private CurrencyRepository repository;
Object target;
Logger logger = LoggerFactory.getLogger(CurrencysService.class);
@Async("taskExecutor")
public CompletableFuture<List<Currencys>> findAllUsers() throws InterruptedException{
LOGGER.info("Request to get a list of cars");
List<Currencys> currencys = repository.findAll();
if (currencys == null || currencys.isEmpty()) {
throw new NoContentException("Tidak ada data Mata Uang");
}
Thread.sleep(1000L);
return CompletableFuture.completedFuture(currencys);
}
}
Dengan dilakukan Debugging pada font yang sudah saya beri warna merah. hasil currencys berupa null, yang mana pada code sebelumnya datanya ada.
0
625
Kutip
3
Balasan
Komentar yang asik ya
Urutan
Terbaru
Terlama
Komentar yang asik ya
Komunitas Pilihan