Compare commits
2 Commits
feature/fi
...
jpa_study
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73703c10a5 | ||
|
|
e736b92975 |
@@ -115,8 +115,3 @@ alter table user_roles
|
||||
- https://daddyprogrammer.org/post/2695/springboot2-simple-jpa-board/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/feature/board
|
||||
- SpringBoot2로 Rest api 만들기(15) – Redis로 api 결과 캐싱(Caching)처리
|
||||
- Document
|
||||
- https://daddyprogrammer.org/post/3870/spring-rest-api-redis-caching/
|
||||
- Git
|
||||
- https://github.com/codej99/SpringRestApi/tree/cache-data-redis
|
||||
|
||||
@@ -26,9 +26,6 @@ dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-actuator'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
|
||||
//embedded-redis
|
||||
implementation 'it.ozimov:embedded-redis:0.7.2'
|
||||
implementation 'io.jsonwebtoken:jjwt:0.9.1'
|
||||
implementation 'io.springfox:springfox-swagger2:2.6.1'
|
||||
implementation 'io.springfox:springfox-swagger-ui:2.6.1'
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.rest.api.common;
|
||||
|
||||
public class CacheKey {
|
||||
|
||||
public static final int DEFAULT_EXPIRE_SEC = 60; // 1 minutes
|
||||
public static final String USER = "user";
|
||||
public static final int USER_EXPIRE_SEC = 60 * 5; // 5 minutes
|
||||
public static final String BOARD = "board";
|
||||
public static final int BOARD_EXPIRE_SEC = 60 * 10; // 10 minutes
|
||||
public static final String POST = "post";
|
||||
public static final String POSTS = "posts";
|
||||
public static final int POST_EXPIRE_SEC = 60 * 5; // 5 minutes
|
||||
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package com.rest.api.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import redis.embedded.RedisServer;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
|
||||
/**
|
||||
* 로컬 환경일경우 내장 레디스가 실행된다.
|
||||
*/
|
||||
@Profile("local")
|
||||
@Configuration
|
||||
public class EmbeddedRedisConfig {
|
||||
|
||||
@Value("${spring.redis.port}")
|
||||
private int redisPort;
|
||||
|
||||
private RedisServer redisServer;
|
||||
|
||||
@PostConstruct
|
||||
public void redisServer() {
|
||||
redisServer = new RedisServer(redisPort);
|
||||
redisServer.start();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void stopRedis() {
|
||||
if (redisServer != null) {
|
||||
redisServer.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.rest.api.config;
|
||||
|
||||
import com.rest.api.common.CacheKey;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.cache.CacheKeyPrefix;
|
||||
import org.springframework.data.redis.cache.RedisCacheConfiguration;
|
||||
import org.springframework.data.redis.cache.RedisCacheManager;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.RedisSerializationContext;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@EnableCaching
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
@Bean(name = "cacheManager")
|
||||
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
|
||||
|
||||
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
|
||||
.disableCachingNullValues()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.DEFAULT_EXPIRE_SEC))
|
||||
.computePrefixWith(CacheKeyPrefix.simple())
|
||||
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
|
||||
|
||||
Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
|
||||
// 캐시 default 유효시간 설정
|
||||
cacheConfigurations.put(CacheKey.USER, RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.USER_EXPIRE_SEC)));
|
||||
cacheConfigurations.put(CacheKey.BOARD, RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.BOARD_EXPIRE_SEC)));
|
||||
cacheConfigurations.put(CacheKey.POST, RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.POST_EXPIRE_SEC)));
|
||||
cacheConfigurations.put(CacheKey.POSTS, RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(CacheKey.POST_EXPIRE_SEC)));
|
||||
|
||||
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory).cacheDefaults(configuration)
|
||||
.withInitialCacheConfigurations(cacheConfigurations).build();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.rest.api.config.security;
|
||||
|
||||
import com.rest.api.entity.User;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jws;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
@@ -9,12 +8,15 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.*;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
@@ -23,7 +25,7 @@ public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
|
||||
@Value("${spring.jwt.secret}")
|
||||
private String secretKey;
|
||||
|
||||
private long tokenValidMilisecond = 1000L * 60 * 60 * 24; // 24시간만 토큰 유효
|
||||
private long tokenValidMilisecond = 1000L * 60 * 60; // 1시간만 토큰 유효
|
||||
|
||||
private final UserDetailsService userDetailsService;
|
||||
|
||||
@@ -47,18 +49,13 @@ public class JwtTokenProvider { // JWT 토큰을 생성 및 검증 모듈
|
||||
|
||||
// Jwt 토큰으로 인증 정보를 조회
|
||||
public Authentication getAuthentication(String token) {
|
||||
Map<String, Object> parseInfo = getUserParseInfo(token);
|
||||
User user = User.builder().uid(String.valueOf(parseInfo.get("msrl"))).roles((List)parseInfo.get("authorities")).build();
|
||||
return new UsernamePasswordAuthenticationToken(user, "", user.getAuthorities());
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(this.getUserPk(token));
|
||||
return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
|
||||
}
|
||||
|
||||
// Jwt 토큰에서 회원 구별 정보 추출
|
||||
public Map<String, Object> getUserParseInfo(String token) {
|
||||
Jws<Claims> parseInfo = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("msrl", parseInfo.getBody().getSubject());
|
||||
result.put("authorities", parseInfo.getBody().get("roles", List.class));
|
||||
return result;
|
||||
public String getUserPk(String token) {
|
||||
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
|
||||
}
|
||||
|
||||
// Request의 Header에서 token 파싱 : "X-AUTH-TOKEN: jwt토큰"
|
||||
|
||||
@@ -1,43 +1,56 @@
|
||||
package com.rest.api.controller;
|
||||
|
||||
import com.rest.api.entity.Employ;
|
||||
import com.rest.api.entity.Member;
|
||||
import com.rest.api.repo.EmployJpaRepo;
|
||||
import com.rest.api.repo.MemberJpaRepo;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@Controller
|
||||
public class HelloController {
|
||||
|
||||
private static final String HELLO = "helloworld-nice to meet you";
|
||||
|
||||
private final EmployJpaRepo employJpaRepo;
|
||||
private final MemberJpaRepo memberJpaRepo;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
private static class Hello {
|
||||
public static class Hello {
|
||||
private String message;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/helloworld/string")
|
||||
@ResponseBody
|
||||
public String helloworldString() {
|
||||
public Employ helloworldString() {
|
||||
|
||||
Employ employ = Employ.builder().employee(memberJpaRepo.findById(1L).get()).build();
|
||||
employ = employJpaRepo.save(employ);
|
||||
log.debug("Helloworld");
|
||||
log.info("Helloworld");
|
||||
return HELLO;
|
||||
return employ;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/helloworld/json")
|
||||
@ResponseBody
|
||||
public Hello helloworldJson() {
|
||||
Hello hello = new Hello();
|
||||
hello.message = HELLO;
|
||||
return hello;
|
||||
public Employ helloworldJson() {
|
||||
return employJpaRepo.findById(2L).get();
|
||||
}
|
||||
|
||||
@GetMapping(value = "/helloworld/page")
|
||||
public String helloworld() {
|
||||
return "helloworld";
|
||||
memberJpaRepo.save(Member.builder().email("happydaddy@naver.com").name("happydaddy").build());
|
||||
memberJpaRepo.save(Member.builder().email("angrydaddy@naver.com").name("angrydaddy").build());
|
||||
return "true";
|
||||
// return HELLO;
|
||||
}
|
||||
|
||||
@GetMapping("/helloworld/long-process")
|
||||
|
||||
@@ -40,8 +40,9 @@ public class UserController {
|
||||
public SingleResult<User> findUser() {
|
||||
// SecurityContext에서 인증받은 회원의 정보를 얻어온다.
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
String id = authentication.getName();
|
||||
// 결과데이터가 단일건인경우 getSingleResult를 이용해서 결과를 출력한다.
|
||||
return responseService.getSingleResult(userJpaRepo.findById(Long.valueOf(authentication.getName())).orElseThrow(CUserNotFoundException::new));
|
||||
return responseService.getSingleResult(userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new));
|
||||
}
|
||||
|
||||
@ApiImplicitParams({
|
||||
@@ -53,7 +54,8 @@ public class UserController {
|
||||
@ApiParam(value = "회원이름", required = true) @RequestParam String name) {
|
||||
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
User user = userJpaRepo.findById(Long.valueOf(authentication.getName())).orElseThrow(CUserNotFoundException::new);
|
||||
String id = authentication.getName();
|
||||
User user = userJpaRepo.findByUid(id).orElseThrow(CUserNotFoundException::new);
|
||||
user.setName(name);
|
||||
return responseService.getSingleResult(userJpaRepo.save(user));
|
||||
}
|
||||
|
||||
@@ -28,15 +28,6 @@ public class BoardController {
|
||||
private final BoardService boardService;
|
||||
private final ResponseService responseService;
|
||||
|
||||
@ApiImplicitParams({
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "게시판 생성", notes = "신규 게시판을 생성한다.")
|
||||
@PostMapping(value = "/{boardName}")
|
||||
public SingleResult<Board> createBoard(@PathVariable String boardName) {
|
||||
return responseService.getSingleResult(boardService.insertBoard(boardName));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "게시판 정보 조회", notes = "게시판 정보를 조회한다.")
|
||||
@GetMapping(value = "/{boardName}")
|
||||
public SingleResult<Board> boardInfo(@PathVariable String boardName) {
|
||||
@@ -53,10 +44,11 @@ public class BoardController {
|
||||
@ApiImplicitParam(name = "X-AUTH-TOKEN", value = "로그인 성공 후 access_token", required = true, dataType = "String", paramType = "header")
|
||||
})
|
||||
@ApiOperation(value = "게시글 작성", notes = "게시글을 작성한다.")
|
||||
@PostMapping(value = "/{boardName}/post")
|
||||
@PostMapping(value = "/{boardName}")
|
||||
public SingleResult<Post> post(@PathVariable String boardName, @Valid @ModelAttribute ParamsPost post) {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
return responseService.getSingleResult(boardService.writePost(Long.valueOf(authentication.getName()), boardName, post));
|
||||
String uid = authentication.getName();
|
||||
return responseService.getSingleResult(boardService.writePost(uid, boardName, post));
|
||||
}
|
||||
|
||||
@ApiOperation(value = "게시글 상세", notes = "게시글 상세정보를 조회한다.")
|
||||
@@ -72,7 +64,8 @@ public class BoardController {
|
||||
@PutMapping(value = "/post/{postId}")
|
||||
public SingleResult<Post> post(@PathVariable long postId, @Valid @ModelAttribute ParamsPost post) {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
return responseService.getSingleResult(boardService.updatePost(postId, Long.valueOf(authentication.getName()), post));
|
||||
String uid = authentication.getName();
|
||||
return responseService.getSingleResult(boardService.updatePost(postId, uid, post));
|
||||
}
|
||||
|
||||
@ApiImplicitParams({
|
||||
@@ -82,7 +75,8 @@ public class BoardController {
|
||||
@DeleteMapping(value = "/post/{postId}")
|
||||
public CommonResult deletePost(@PathVariable long postId) {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
boardService.deletePost(postId, Long.valueOf(authentication.getName()));
|
||||
String uid = authentication.getName();
|
||||
boardService.deletePost(postId, uid);
|
||||
return responseService.getSuccessResult();
|
||||
}
|
||||
}
|
||||
|
||||
29
src/main/java/com/rest/api/entity/Employ.java
Normal file
29
src/main/java/com/rest/api/entity/Employ.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.rest.api.entity;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Getter
|
||||
public class Employ {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long employId;
|
||||
@OneToOne
|
||||
@JoinColumn(name = "employer_id")
|
||||
private Member employer;
|
||||
@OneToOne
|
||||
@JoinColumn(name = "employee_id")
|
||||
private Member employee;
|
||||
|
||||
@Builder
|
||||
public Employ(Member employer, Member employee) {
|
||||
this.employer = employer;
|
||||
this.employee = employee;
|
||||
}
|
||||
}
|
||||
28
src/main/java/com/rest/api/entity/Member.java
Normal file
28
src/main/java/com/rest/api/entity/Member.java
Normal file
@@ -0,0 +1,28 @@
|
||||
package com.rest.api.entity;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.Date;
|
||||
|
||||
@NoArgsConstructor
|
||||
@Entity
|
||||
@Getter
|
||||
public class Member {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long uid;
|
||||
@Column(name = "email", unique = true)
|
||||
private String email;
|
||||
private String name;
|
||||
private Date createDate;
|
||||
|
||||
@Builder
|
||||
public Member(String email, String name) {
|
||||
this.email = email;
|
||||
this.name = name;
|
||||
this.createDate = new Date();
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.rest.api.entity.common.CommonDateEntity;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.Proxy;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
@@ -23,7 +22,6 @@ import java.util.stream.Collectors;
|
||||
@AllArgsConstructor // 인자를 모두 갖춘 생성자를 자동으로 생성합니다.
|
||||
@Table(name = "user") // 'user' 테이블과 매핑됨을 명시
|
||||
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) // Post Entity에서 User와의 관계를 Json으로 변환시 오류 방지를 위한 코드
|
||||
@Proxy(lazy = false)
|
||||
public class User extends CommonDateEntity implements UserDetails {
|
||||
@Id // pk
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
|
||||
@@ -1,20 +1,15 @@
|
||||
package com.rest.api.entity.board;
|
||||
|
||||
import com.rest.api.entity.common.CommonDateEntity;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Builder
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Board extends CommonDateEntity implements Serializable {
|
||||
public class Board extends CommonDateEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long boardId;
|
||||
|
||||
@@ -1,21 +1,16 @@
|
||||
package com.rest.api.entity.board;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.rest.api.entity.User;
|
||||
import com.rest.api.entity.common.CommonDateEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import org.hibernate.annotations.Proxy;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class Post extends CommonDateEntity implements Serializable {
|
||||
public class Post extends CommonDateEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long postId;
|
||||
@@ -30,13 +25,13 @@ public class Post extends CommonDateEntity implements Serializable {
|
||||
@JoinColumn(name = "board_id")
|
||||
private Board board; // 게시글 - 게시판의 관계 - N:1
|
||||
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "msrl")
|
||||
private User user; // 게시글 - 회원의 관계 - N:1
|
||||
|
||||
// Join 테이블이 Json결과에 표시되지 않도록 처리.
|
||||
@JsonIgnore
|
||||
public Board getBoard() {
|
||||
protected Board getBoard() {
|
||||
return board;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,13 +7,12 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
|
||||
import javax.persistence.EntityListeners;
|
||||
import javax.persistence.MappedSuperclass;
|
||||
import java.io.Serializable;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Getter
|
||||
@MappedSuperclass
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public abstract class CommonDateEntity implements Serializable {
|
||||
public abstract class CommonDateEntity {
|
||||
@CreatedDate
|
||||
private LocalDateTime createdAt;
|
||||
@LastModifiedDate
|
||||
|
||||
7
src/main/java/com/rest/api/repo/EmployJpaRepo.java
Normal file
7
src/main/java/com/rest/api/repo/EmployJpaRepo.java
Normal file
@@ -0,0 +1,7 @@
|
||||
package com.rest.api.repo;
|
||||
|
||||
import com.rest.api.entity.Employ;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface EmployJpaRepo extends JpaRepository<Employ, Long> {
|
||||
}
|
||||
7
src/main/java/com/rest/api/repo/MemberJpaRepo.java
Normal file
7
src/main/java/com/rest/api/repo/MemberJpaRepo.java
Normal file
@@ -0,0 +1,7 @@
|
||||
package com.rest.api.repo;
|
||||
|
||||
import com.rest.api.entity.Member;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface MemberJpaRepo extends JpaRepository<Member, Long> {
|
||||
}
|
||||
@@ -7,5 +7,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface PostJpaRepo extends JpaRepository<Post, Long> {
|
||||
List<Post> findByBoardOrderByPostIdDesc(Board board);
|
||||
List<Post> findByBoard(Board board);
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package com.rest.api.service.board;
|
||||
import com.rest.api.advice.exception.CNotOwnerException;
|
||||
import com.rest.api.advice.exception.CResourceNotExistException;
|
||||
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||
import com.rest.api.common.CacheKey;
|
||||
import com.rest.api.entity.User;
|
||||
import com.rest.api.entity.board.Board;
|
||||
import com.rest.api.entity.board.Post;
|
||||
@@ -11,19 +10,13 @@ import com.rest.api.model.board.ParamsPost;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import com.rest.api.repo.board.BoardJpaRepo;
|
||||
import com.rest.api.repo.board.PostJpaRepo;
|
||||
import com.rest.api.service.cache.CacheSevice;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.transaction.Transactional;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@Transactional
|
||||
@RequiredArgsConstructor
|
||||
@@ -32,60 +25,47 @@ public class BoardService {
|
||||
private final BoardJpaRepo boardJpaRepo;
|
||||
private final PostJpaRepo postJpaRepo;
|
||||
private final UserJpaRepo userJpaRepo;
|
||||
private final CacheSevice cacheSevice;
|
||||
|
||||
public Board insertBoard(String boardName) {
|
||||
return boardJpaRepo.save(Board.builder().name(boardName).build());
|
||||
}
|
||||
|
||||
// 게시판 이름으로 게시판을 조회. 없을경우 CResourceNotExistException 처리
|
||||
@Cacheable(value = CacheKey.BOARD, key = "#boardName", unless = "#result == null")
|
||||
public Board findBoard(String boardName) {
|
||||
return Optional.ofNullable(boardJpaRepo.findByName(boardName)).orElseThrow(CResourceNotExistException::new);
|
||||
}
|
||||
|
||||
// 게시판 이름으로 게시글 리스트 조회.
|
||||
@Cacheable(value = CacheKey.POSTS, key = "#boardName", unless = "#result == null")
|
||||
// 게시판 이름으로 게시물 리스트 조회.
|
||||
public List<Post> findPosts(String boardName) {
|
||||
return postJpaRepo.findByBoardOrderByPostIdDesc(findBoard(boardName));
|
||||
return postJpaRepo.findByBoard(findBoard(boardName));
|
||||
}
|
||||
|
||||
// 게시글ID로 게시글 단건 조회. 없을경우 CResourceNotExistException 처리
|
||||
@Cacheable(value = CacheKey.POST, key = "#postId", unless = "#result == null")
|
||||
// 게시물ID로 게시물 단건 조회. 없을경우 CResourceNotExistException 처리
|
||||
public Post getPost(long postId) {
|
||||
return postJpaRepo.findById(postId).orElseThrow(CResourceNotExistException::new);
|
||||
}
|
||||
|
||||
// 게시글을 등록합니다. 게시글의 회원UID가 조회되지 않으면 CUserNotFoundException 처리합니다.
|
||||
@CacheEvict(value = CacheKey.POSTS, key = "#boardName")
|
||||
public Post writePost(Long msrl, String boardName, ParamsPost paramsPost) {
|
||||
// 게시물을 등록합니다. 게시물의 회원UID가 조회되지 않으면 CUserNotFoundException 처리합니다.
|
||||
public Post writePost(String uid, String boardName, ParamsPost paramsPost) {
|
||||
Board board = findBoard(boardName);
|
||||
Post post = new Post(userJpaRepo.findById(msrl).orElseThrow(CUserNotFoundException::new), board, paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
|
||||
Post post = new Post(userJpaRepo.findByUid(uid).orElseThrow(CUserNotFoundException::new), board, paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
|
||||
return postJpaRepo.save(post);
|
||||
}
|
||||
|
||||
// 게시글을 수정합니다. 게시글 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
|
||||
//@CachePut(value = CacheKey.POST, key = "#postId") 갱신된 정보만 캐시할경우에만 사용!
|
||||
public Post updatePost(long postId, Long msrl, ParamsPost paramsPost) {
|
||||
// 게시물을 수정합니다. 게시물 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
|
||||
public Post updatePost(long postId, String uid, ParamsPost paramsPost) {
|
||||
Post post = getPost(postId);
|
||||
User user = post.getUser();
|
||||
if (!msrl.equals(user.getMsrl()))
|
||||
if (!uid.equals(user.getUid()))
|
||||
throw new CNotOwnerException();
|
||||
|
||||
// 영속성 컨텍스트의 변경감지(dirty checking) 기능에 의해 조회한 Post내용을 변경만 해도 Update쿼리가 실행됩니다.
|
||||
post.setUpdate(paramsPost.getAuthor(), paramsPost.getTitle(), paramsPost.getContent());
|
||||
cacheSevice.deleteBoardCache(post.getPostId(), post.getBoard().getName());
|
||||
return post;
|
||||
}
|
||||
|
||||
// 게시글을 삭제합니다. 게시글 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
|
||||
public boolean deletePost(long postId, Long msrl) {
|
||||
// 게시물을 삭제합니다. 게시물 등록자와 로그인 회원정보가 틀리면 CNotOwnerException 처리합니다.
|
||||
public boolean deletePost(long postId, String uid) {
|
||||
Post post = getPost(postId);
|
||||
User user = post.getUser();
|
||||
if (!msrl.equals(user.getMsrl()))
|
||||
if (!uid.equals(user.getUid()))
|
||||
throw new CNotOwnerException();
|
||||
postJpaRepo.delete(post);
|
||||
cacheSevice.deleteBoardCache(post.getPostId(), post.getBoard().getName());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.rest.api.service.cache;
|
||||
|
||||
import com.rest.api.common.CacheKey;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Caching;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CacheSevice {
|
||||
|
||||
@Caching(evict = {
|
||||
@CacheEvict(value = CacheKey.POST, key = "#postId"),
|
||||
@CacheEvict(value = CacheKey.POSTS, key = "#boardName")
|
||||
})
|
||||
public boolean deleteBoardCache(long postId, String boardName) {
|
||||
log.debug("deleteBoardCache - postId {}, boardName {}", postId, boardName);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
package com.rest.api.service.security;
|
||||
|
||||
import com.rest.api.advice.exception.CUserNotFoundException;
|
||||
import com.rest.api.common.CacheKey;
|
||||
import com.rest.api.repo.UserJpaRepo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -15,7 +13,6 @@ public class CustomUserDetailService implements UserDetailsService {
|
||||
|
||||
private final UserJpaRepo userJpaRepo;
|
||||
|
||||
@Cacheable(value = CacheKey.USER, key = "#userPk", unless = "#result == null")
|
||||
public UserDetails loadUserByUsername(String userPk) {
|
||||
return userJpaRepo.findById(Long.valueOf(userPk)).orElseThrow(CUserNotFoundException::new);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,4 @@ spring:
|
||||
showSql: true
|
||||
generate-ddl: false
|
||||
url:
|
||||
base: http://dev-api.daddyprogrammer.org
|
||||
redis:
|
||||
host: Standalone Redis 호스트
|
||||
port: Standalone Redis 포트
|
||||
base: http://dev-api.daddyprogrammer.org
|
||||
@@ -18,6 +18,3 @@ spring:
|
||||
generate-ddl: true
|
||||
url:
|
||||
base: http://localhost:8080
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
67
src/test/java/com/rest/api/cache/CacheRepo.java
vendored
67
src/test/java/com/rest/api/cache/CacheRepo.java
vendored
@@ -1,67 +0,0 @@
|
||||
package com.rest.api.cache;
|
||||
|
||||
import com.rest.api.entity.board.Post;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class CacheRepo {
|
||||
|
||||
private static final String CACHE_KEY = "CACHE_TEST";
|
||||
|
||||
@Cacheable(value = CACHE_KEY, key = "#postId")
|
||||
public Post getPost(long postId) {
|
||||
Post post = new Post();
|
||||
post.setPostId(postId);
|
||||
post.setTitle("title_" + postId);
|
||||
post.setAuthor("author_" + postId);
|
||||
post.setContent("content_" + postId);
|
||||
return post;
|
||||
}
|
||||
|
||||
@CachePut(value = CACHE_KEY, key = "#post.postId")
|
||||
public Post updatePost(Post post) {
|
||||
return post;
|
||||
}
|
||||
|
||||
@Cacheable(value = CACHE_KEY, key = "{#postId, #title}")
|
||||
public Post getPostMultiKey(long postId, String title) {
|
||||
Post post = new Post();
|
||||
post.setPostId(postId);
|
||||
post.setTitle("title_" + postId);
|
||||
post.setAuthor("author_" + postId);
|
||||
post.setContent("content_" + postId);
|
||||
return post;
|
||||
}
|
||||
|
||||
@CachePut(value = CACHE_KEY, key = "{#post.postId, #post.title}")
|
||||
// @CachePut(value = CACHE_KEY, key = "{#post.postId, #post.getTitle()}")
|
||||
public Post updatePostMultiKey(Post post) {
|
||||
return post;
|
||||
}
|
||||
|
||||
@CacheEvict(cacheNames = {CACHE_KEY}, allEntries = true)
|
||||
public void clearCache(){}
|
||||
|
||||
@Cacheable(value = CACHE_KEY, key = "{#postId}", condition="#postId > 10")
|
||||
public Post getPostCondition(long postId) {
|
||||
Post post = new Post();
|
||||
post.setPostId(postId);
|
||||
post.setTitle("title_" + postId);
|
||||
post.setAuthor("author_" + postId);
|
||||
post.setContent("content_" + postId);
|
||||
return post;
|
||||
}
|
||||
|
||||
@Cacheable(value = CACHE_KEY, key = "T(com.rest.api.cache.CustomKeyGenerator).create(#postId, #title)")
|
||||
public Post getPostKeyGenerator(long postId, String title) {
|
||||
Post post = new Post();
|
||||
post.setPostId(postId);
|
||||
post.setTitle("title_" + postId);
|
||||
post.setAuthor("author_" + postId);
|
||||
post.setContent("content_" + postId);
|
||||
return post;
|
||||
}
|
||||
}
|
||||
67
src/test/java/com/rest/api/cache/CacheTest.java
vendored
67
src/test/java/com/rest/api/cache/CacheTest.java
vendored
@@ -1,67 +0,0 @@
|
||||
package com.rest.api.cache;
|
||||
|
||||
import com.rest.api.entity.board.Post;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class CacheTest {
|
||||
|
||||
@Autowired
|
||||
private CacheRepo cacheRepo;
|
||||
|
||||
@Test
|
||||
public void cacheTest() throws Exception {
|
||||
// get cache
|
||||
Post post = cacheRepo.getPost(1L);
|
||||
assertSame(1L, post.getPostId());
|
||||
assertEquals("title_1", post.getTitle());
|
||||
// update cache
|
||||
post.setTitle("title_modified");
|
||||
post.setContent("content_modified");
|
||||
cacheRepo.updatePost(post);
|
||||
// get cache
|
||||
Post postModified = cacheRepo.getPost(1L);
|
||||
assertEquals("title_modified", postModified.getTitle());
|
||||
assertEquals("content_modified", postModified.getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cacheTestMultiKey() throws Exception {
|
||||
// get cache
|
||||
Post post = cacheRepo.getPostMultiKey(1L, "title_1");
|
||||
assertSame(1L, post.getPostId());
|
||||
assertEquals("title_1", post.getTitle());
|
||||
// update cache
|
||||
post.setTitle("title_modified");
|
||||
post.setContent("content_modified");
|
||||
cacheRepo.updatePostMultiKey(post);
|
||||
// get cache
|
||||
Post postModified = cacheRepo.getPostMultiKey(1L, "title_modified");
|
||||
assertEquals("title_modified", postModified.getTitle());
|
||||
assertEquals("content_modified", postModified.getContent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cacheTestCustomKeyGenerator() throws Exception {
|
||||
// get cache
|
||||
Post post = cacheRepo.getPostKeyGenerator(1L, "title_1");
|
||||
assertSame(1L, post.getPostId());
|
||||
assertEquals("title_1", post.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteAllCache() {
|
||||
cacheRepo.getPost(1L);
|
||||
cacheRepo.getPost(2L);
|
||||
cacheRepo.getPost(3L);
|
||||
cacheRepo.getPost(4L);
|
||||
cacheRepo.clearCache();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.rest.api.cache;
|
||||
|
||||
public class CustomKeyGenerator {
|
||||
public static Object create(Object o1, Object o2) {
|
||||
return "FRONT:" + o1 + ":" + o2;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user