Category: Spring

0

Spring Cloud - 21. Spring Cloud Config 연동 Actuactor

목차 Spring Cloud - 25. Spring Cloud Config Native Spring Cloud - 24. Client Service 에서 Config Server 연동하기 Spring Cloud - 23. Spring Cloud Config Server 만들기 Spring Cloud - 22. Spring Cloud Config 연동 Actuator 2 Spring Cloud - 21. Spring Cloud Config 연동 Actuactor 참고 https://www.baeldung.com/spring-cloud-config-without-git https://mangkyu.tistory.com/253 Spring Cloud Config ServerSpring Cloud Config Server 의존성 추가// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-config-server'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' /{application}/{profile}[/{label}]/{application}-{profile}.yml/{label}/{application}-{profile}.yml/{application}-{profile}.properties/{label}/{application}-{profile}.properties @EnableConfigServer 어노테이션을 추가하여 Config Server를 만들어 준다.

0

Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice AuthorizationHeaderFilter 추가@Component@Slf4jpublic class AuthorizationHeaderFilter extends AbstractGatewayFilterFactory<AuthorizationHeaderFilter.Config> { private Environment env; public AuthorizationHeaderFilter(Environment env){ super(Config.class); this.env = env; } // login -> token -> users (with token) -> header(include token) @Override public GatewayFilter apply(Config config) { return ((exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); if(!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)){ return onError(exchange, "No Authorization Header", HttpStatus.UNAUTHORIZED); } String authorizationHeader = request.getHeaders().get(HttpHeaders.AUTHORIZATION).get(0); String jwt = authorizationHeader.replace("Bearer ", ""); if(!isJwtValid(jwt)){ return onError(exchange, "JWT token is not valid", HttpStatus.UNAUTHORIZED); } return chain.filter(exchange); }); } private boolean isJwtValid(String jwt){ boolean returnValue = true; String subject = null; String key = env.getProperty("token.secret"); try { subject = Jwts.parser() .setSigningKey(env.getProperty("token.secret")) .parseClaimsJws(jwt).getBody() .getSubject(); } catch (Exception ex){ returnValue = false; } if(subject == null || subject.isEmpty()){ returnValue = false; } return returnValue; } private Mono<Void> onError(ServerWebExchange exchange, String error, HttpStatus httpStatus) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(httpStatus); log.error(error); return response.setComplete(); } public static class Config{ }} // https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1' server: port: 8080eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekaspring: application: name: apigateway-service cloud: gateway: default-filters: - name: GlobalFilter args: baseMessage: Spring Cloud Gateway Global Filter preLogger: true postLogger: true routes:# - id: user-service# uri: lb://USER-SERVICE# predicates:# - Path=/user-service/**# filters:# - CustomFilter - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/login - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/users - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/** - Method=GET filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - AuthorizationHeaderFilter - id: catalog-service uri: lb://CATALOG-SERVICE predicates: - Path=/catalog-service/** filters: - CustomFilter - id: order-service uri: lb://ORDER-SERVICE predicates: - Path=/order-service/** filters: - CustomFiltertoken: secret: user_token

0

Spring Cloud - 19. Users Microservice JWT 생성

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice JWT 생성// https://mvnrepository.com/artifact/io.jsonwebtoken/jjwtimplementation group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1' @Slf4jpublic class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { private UserService userService; private Environment env; public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService, Environment env){ super.setAuthenticationManager( authenticationManager); this.userService = userService; this.env = env; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class); Authentication token = new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getPassword(), new ArrayList<>()); return getAuthenticationManager().authenticate(token); } catch (IOException e){ throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String username = ((User)authResult.getPrincipal()).getUsername(); UserDto userDetails = userService.getUserDetailsByEmail(username); String token = Jwts.builder() .setSubject(userDetails.getUserId()) .setExpiration(new Date(System.currentTimeMillis() + Long.parseLong(env.getProperty("token.expiration_time")))) .signWith(SignatureAlgorithm.HS512, env.getProperty("token.secret")) .compact(); response.addHeader("token", token); response.addHeader("userId", userDetails.getUserId()); }}

0

Spring Cloud - 18. Users Microservice 로그인 성공 처리

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice 로그인 성공 처리@Slf4jpublic class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { private UserService userService; private Environment env; public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService, Environment env){ super(authenticationManager); this.userService = userService; this.env = env; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class); Authentication token = new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getPassword(), new ArrayList<>()); return getAuthenticationManager().authenticate(token); } catch (IOException e){ throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String username = ((User)authResult.getPrincipal()).getUsername(); UserDto userDetails = userService.getUserDetailsByEmail(username); }} @Configuration@EnableWebSecuritypublic class WebSecurity extends WebSecurityConfigurerAdapter { private Environment env; private UserService userService; private BCryptPasswordEncoder bCryptPasswordEncoder; public WebSecurity(Environment evn, UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder){ this.env = env; this.userService = userService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests().antMatchers("/users/**") .hasIpAddress("192.168.0.2") .and() .addFilter(getAuthenticationFilter()); http.headers().frameOptions().disable(); } private AuthenticationFilter getAuthenticationFilter() throws Exception{ AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager(), userService, env); return authenticationFilter; }} public interface UserService extends UserDetailsService { UserDto createUser(UserDto userDto); UserDto getUserByUserId(String userId); Iterable<UserEntity> getUserByAll(); UserDto getUserDetailsByEmail(String username);} @Servicepublic class UserServiceImpl implements UserService { UserRepository userRepository; BCryptPasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userEntity = userRepository.findByEmail(username); if (userEntity == null) { throw new UsernameNotFoundException(username); } return new User(userEntity.getEmail() , userEntity.getEncryptedPwd() , true , true , true , true , new ArrayList<>()); } public UserServiceImpl(UserRepository userRepository, BCryptPasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } @Override public UserDto createUser(UserDto userDto) { userDto.setUserId(UUID.randomUUID().toString()); ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); UserEntity userEntity = modelMapper.map(userDto, UserEntity.class); userEntity.setEncryptedPwd(passwordEncoder.encode(userDto.getPwd())); userRepository.save(userEntity); UserDto returnUserDto = modelMapper.map(userEntity, UserDto.class); return returnUserDto; } @Override public UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); List<ResponseOrder> orders = new ArrayList<>(); userDto.setOrders(orders); return userDto; } @Override public Iterable<UserEntity> getUserByAll() { return userRepository.findAll(); } @Override public UserDto getUserDetailsByEmail(String email) { UserEntity userEntity = userRepository.findByEmail(email); if(userEntity == null){ throw new UsernameNotFoundException(email); } UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); return userDto; }}

0

Spring Cloud - 17. Users Microservice Routes 정보 변경

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice Routes 정보 변경server: port: 8080eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekaspring: application: name: apigateway-service cloud: gateway: default-filters: - name: GlobalFilter args: baseMessage: Spring Cloud Gateway Global Filter preLogger: true postLogger: true routes:# - id: user-service# uri: lb://USER-SERVICE# predicates:# - Path=/user-service/**# filters:# - CustomFilter - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/login - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/users - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/** - Method=GET filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: catalog-service uri: lb://CATALOG-SERVICE predicates: - Path=/catalog-service/** filters: - CustomFilter - id: order-service uri: lb://ORDER-SERVICE predicates: - Path=/order-service/** filters: - CustomFilter

0

Spring Cloud - 16. Users Microservice loadUserByUsername() 구현

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice loadUserByUsername() 구현public interface UserService extends UserDetailsService { UserDto createUser(UserDto userDto); UserDto getUserByUserId(String userId); Iterable<UserEntity> getUserByAll();} public interface UserRepository extends CrudRepository<UserEntity, Long> { UserEntity findByUserId(String userId); UserEntity findByEmail(String username);} @Servicepublic class UserServiceImpl implements UserService { UserRepository userRepository; BCryptPasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userEntity = userRepository.findByEmail(username); if (UserEntity == null) { throw new UsernameNotFoundException(username); } return new User(userEntity.getEmail() , userEntity.getEncryptedPwd() , true , true , true , true , new ArrayList<>()); } public UserServiceImpl(UserRepository userRepository, BCryptPasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } @Override public UserDto createUser(UserDto userDto) { userDto.setUserId(UUID.randomUUID().toString()); ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); UserEntity userEntity = modelMapper.map(userDto, UserEntity.class); userEntity.setEncryptedPwd(passwordEncoder.encode(userDto.getPwd())); userRepository.save(userEntity); UserDto returnUserDto = modelMapper.map(userEntity, UserDto.class); return returnUserDto; } @Override public UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); List<ResponseOrder> orders = new ArrayList<>(); userDto.setOrders(orders); return userDto; } @Override public Iterable<UserEntity> getUserByAll() { return userRepository.findAll(); }} @Configuration@EnableWebSecuritypublic class WebSecurity extends WebSecurityConfigurerAdapter { private Environment env; private UserService userService; private BCryptPasswordEncoder bCryptPasswordEncoder; public WebSecurity(Environment evn, UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder){ this.env = env; this.userService = userService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests().antMatchers("/users/**") .hasIpAddress("192.168.0.2") .and() .addFilter(getAuthenticationFilter()); http.headers().frameOptions().disable(); } private AuthenticationFilter getAuthenticationFilter() throws Exception{ AuthenticationFilter authenticationFilter = new AuthenticationFilter(); authenticationFilter.setAuthenticationManager(authenticationManager()); return authenticationFilter; } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }}

0

Spring Cloud - 15. Users Microservice AuthenticationFilter

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice 15. Users Microservice AuthenticationFilter@Datapublic class RequestLogin { @NotNull(message = "Email cannot be null") @Size(min = 2, message = "Email not be less than two characters") private String email; @NotNull(message = "Password cannot be null") @Size(min = 8, message = "Password must be equals or grater than 8 characters") private String password;} public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class); Authentication token = new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getPassword(), new ArrayList<>()); return getAuthenticationManager().authenticate(token); } catch (IOException e){ throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { super.successfulAuthentication(request, response, chain, authResult); }}

0

Spring Cloud - 14. Users Microservice Order Service

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice Order Service설정server: port: 0spring: application: name: order-service h2: console: enabled: true settings: web-allow-others: true datasource: driver-class-name: org.h2.Driver username: sa password: url: jdbc:h2:mem:testdb jpa: hibernate: ddl-auto: create-drop generate-ddl: true show-sql: trueeureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka instance: instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}} @Data@Entity@Table(name = "orders")public class OrderEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 120) private String productId; @Column(nullable = false) private Integer qty; @Column(nullable = false) private Integer unitPrice; @Column(nullable = false) private Integer totalPrice; @Column(nullable = false) private String userId; @Column(nullable = false, unique = true) private String orderId; @Column(nullable = false, updatable = false, insertable = false) @ColumnDefault(value = "CURRENT_TIMESTAMP") private Date createdAt;} @Repositorypublic interface OrderRepository extends CrudRepository<OrderEntity, Long> { OrderEntity findByOrderId(String orderId); Iterable<OrderEntity> findByUserId(String userId);} @Data@JsonInclude(JsonInclude.Include.NON_NULL)public class ResponseOrder { private String productId; private Integer qty; private Integer unitPrice; private Integer totalPrice; private Date createdAt; private String orderId;} @Datapublic class RequestOrder { private String productId; private Integer qty; private Integer unitPrice;}

0

Spring Cloud - 13. Users Microservice Catalog

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice 13. Users Microservice Catalog설정 정보server: port: 0spring: application: name: catalog-service h2: console: enabled: true settings: web-allow-others: true datasource: hikari: driver-class-name: org.h2.Driver url: jdbc:h2:mem:testdb username: sa password: jpa: hibernate: ddl-auto: create-drop show-sql: true generate-ddl: trueeureka: client: service-url: defaultZone: http://localhost:8761/eureka#logging:# level:# com.example.catalogservice: DEBUG @Data@Entity@Table(name = "catalog")public class CatalogEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 120, unique = true) private String productId; @Column(nullable = false) private String productName; @Column(nullable = false) private Integer stock; @Column(nullable = false) private Integer unitPrice; @Column(nullable = false, updatable = false, insertable = false) @ColumnDefault(value = "CURRENT_TIMESTAMP") private Date createdAt;} @Repositorypublic interface CatalogRepository extends CrudRepository<CatalogEntity, Long> { CatalogEntity findByProductId(String productId);} public interface CatalogService { Iterable<CatalogEntity> getAllCatalogs();} @Service@Slf4jpublic class CatalogServiceImpl implements CatalogService{ CatalogRepository repository; Environment env; public CatalogServiceImpl(CatalogRepository repository, Environment env){ this.repository = repository; this.env = env; } @Override public Iterable<CatalogEntity> getAllCatalogs() { return repository.findAll(); }}

0

Spring Cloud - 12. Users Microservice 사용자 조회

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice 12. Users Microservice 사용자 조회@Overridepublic UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); List<ResponseOrder> orders = new ArrayList<>(); userDto.setOrders(orders); return userDto;}@Overridepublic Iterable<UserEntity> getUserByAll() { return userRepository.findAll();} public interface UserRepository extends CrudRepository<UserEntity, Long> { UserEntity findByUserId(String userId);} 전체 User 정보 가져오기@GetMapping("/users")public ResponseEntity<List<ResponseUser>> getUsers() { Iterable<UserEntity> userList = userService.getUserByAll(); List<ResponseUser> result = new ArrayList<>(); userList.forEach(v -> { result.add(new ModelMapper().map(v, ResponseUser.class)); }); return ResponseEntity.status(HttpStatus.OK).body(result);} 특정 User 정보 가져오기@GetMapping("/users/{userId}") public ResponseEntity<ResponseUser> getUsers(@PathVariable("userId") String userId) { UserDto userDto = userService.getUserByUserId(userId); ResponseUser returnValue = new ModelMapper().map(userDto, ResponseUser.class); return ResponseEntity.status(HttpStatus.OK).body(returnValue); }

0

Spring Cloud - 11. Users Microservice Gateway 연동

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice Gateway 연동@GetMapping("/health_check")public String status(){ return String.format("It's Working in User Service on PORT %s", env.getProperty("local.server.port"));} server: port: 8080eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekaspring: application: name: apigateway-service cloud: gateway: default-filters: - name: GlobalFilter args: baseMessage: Spring Cloud Gateway Global Filter preLogger: true postLogger: true routes: - id: user-service # uri: http://localhost:8081/ uri: lb://USER-SERVICE predicates: - Path=/user-service/** filters: - CustomFilter # - AddRequestHeader=first-request, first-request-header2 # - AddResponseHeader=first-response, first-response-header2 - id: first-service # uri: http://localhost:8081/ uri: lb://MY-FIRST-SERVICE predicates: - Path=/first-service/** filters: - CustomFilter # - AddRequestHeader=first-request, first-request-header2 # - AddResponseHeader=first-response, first-response-header2 Gateway를 거처 User Service에 접근하게 되면 문제가 발생 User Service의 URI와 API Gateway의 URI가 다르기 때문에 문제가 생김 @GetMapping("/user-service/health_check")public String status(){ return String.format("It's Working in User Service on PORT %s", env.getProperty("local.server.port"));}

0

Spring Cloud - 10. Users Microservice 사용자 추가

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice 사용자 추가@RestController@RequestMapping("/")public class UserController { private Environment env; private UserService userService; private Greeting greeting; public UserController(Environment env, UserService userService){ this.env = env; this.userService = userService; } @GetMapping("/health_check") public String status(){ return "It's Working in User Service"; } @GetMapping("/welcome") public String welcome(){ return env.getProperty("greeting.message"); } @GetMapping("/welcome_value") public String welcomeValue(){ return greeting.getMessage(); } @PostMapping("/users") public ResponseEntity createUser(@RequestBody RequestUser user){ ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); UserDto userDto = modelMapper.map(user, UserDto.class); userService.createUser(userDto); ResponseUser responseUser = modelMapper.map(userDto, ResponseUser.class); return ResponseEntity.status(HttpStatus.CREATED).body(responseUser); }} @Datapublic class ResponseUser { private String email; private String name; private String userId;} @Datapublic class RequestUser { @NotNull(message = "Email cannot be null") @Size(min = 2, message = "Email not be less than two characters") private String email; @NotNull(message = "Name cannot be null") @Size(min = 2, message = "Name not be less than two characters") private String pwd; @NotNull(message = "Password cannot be null") @Size(min = 8, message = "Password not be less than two characters") private String name;} @Datapublic class UserDto { private String email; private String name; private String pwd; private String userId; private Date createdAt; private String encryptedPwd;} @Component@Data@AllArgsConstructor@NoArgsConstructorpublic class Greeting { @Value("${greeting.message}") private String message;} @Data@Entity@Table("users")public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 50) private String email; @Column(nullable = false, length = 50) private String name; @Column(nullable = false, unique = true) private String userId; @Column(nullable = false, unique = true) private String encryptedPwd;}

0

Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9server: port: 0spring: application: name: user-service h2: console: enabled: true settings: web-allow-others: true datasource: username: sa password: hikari: driver-class-name: org.h2.Driver url: jdbc:h2:mem:testdbeureka: instance: instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}} client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekagreeting: message: Welcome to the Simple E-commerce.n

0

Spring Cloud - Users Microservice

목차 Spring Cloud - 20. Users Microservice AuthorizationHeaderFilter 추가 Spring Cloud - 19. Users Microservice JWT 생성 Spring Cloud - 18. Users Microservice 로그인 성공 처리 Spring Cloud - 17. Users Microservice Routes 정보 변경 Spring Cloud - 16. Users Microservice loadUserByUsername() 구현 Spring Cloud - 15. Users Microservice AuthenticationFilter Spring Cloud - 14. Users Microservice Order Service Spring Cloud - 13. Users Microservice Catalog Spring Cloud - 12. Users Microservice 사용자 조회 Spring Cloud - 11. Users Microservice Gateway 연동 Spring Cloud - 10. Users Microservice 사용자 추가 Spring Cloud로 개발하는 마이크로서비스 애플리케이션 9 Spring Cloud - Users Microservice Users Microservice@RestController@RequestMapping("/")public class UserController { @GetMapping("/health_check") public String status(){ return "It's Working in User Service"; }} 프로젝트 설정 추가하기server: port: 0spring: application: name: user-serviceeureka: instance: instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}} client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka Application.yml 파일로부터 데이터 가져오기server: port: 0spring: application: name: user-serviceeureka: instance: instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}} client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekagreeting: message: Welcome to the Simple E-commerce. Enviroment 객체를 사용하는 방법

0

Spring Cloud - 7. Load Balancer 적용

Spring Cloud - 7. Load Balancer 적용 Spring Cloud - 6. Spring Cloud Gateway Global Filter 적용 Spring Cloud - 5. Spring Cloud Gateway Global Filter 적용 Spring Cloud - 4. Spring Cloud Gateway Custom Filter 적용 Spring Cloud - 3. Spring Cloud Gateway Filter 적용 Spring Cloud - 2. Spring Cloud Gateway 사용하기 Spring Cloud - Eureka 에 Service 등록하기 Spring Cloud - Service Discovery Server (Eureka) Spring Cloud로 개발하는 마이크로서비스 애플리케이션 7 - Load Balancer 적용Spring Cloud Gateway와 Eureka연동 Gateway 설정eureka 설정하기 eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka Gateway 설정하기 spring: application: name: apigateway-service cloud: gateway: default-filters: - name: GlobalFilter args: baseMessage: Spring Cloud Gateway Global Filter preLogger: true postLogger: true routes: - id: first-service# uri: http://localhost:8081/ uri: lb://MY-FIRST-SERVICE predicates: - Path=/first-service/** filters: - CustomFilter# - AddRequestHeader=first-request, first-request-header2# - AddResponseHeader=first-response, first-response-header2 - id: second-service# uri: http://localhost:8082/ uri: lb://MY-SECOND-SERVICE predicates: - Path=/second-service/** filters: - name: CustomFilter - name: LoggingFilter args: baseMessage: Hi, there. preLogger: true postLogger: true# - AddRequestHeader=second-request, second-request-header2# - AddResponseHeader=second-response, second-response-header2 Client 설정