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

127 feat 인기 포트폴리오 방식 변경 #128

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.palettee.gathering.controller.dto.Request.GatheringCommonRequest;
import com.palettee.gathering.controller.dto.Response.GatheringCommonResponse;
import com.palettee.gathering.controller.dto.Response.GatheringDetailsResponse;
import com.palettee.gathering.controller.dto.Response.GatheringPopularResponse;
import com.palettee.gathering.service.GatheringService;
import com.palettee.global.security.validation.UserUtils;
import com.palettee.portfolio.controller.dto.response.CustomSliceResponse;
Expand All @@ -14,6 +15,7 @@
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequiredArgsConstructor
Expand Down Expand Up @@ -88,4 +90,20 @@ public CustomSliceResponse findLike(
return gatheringService.findLikeList(pageable, contextUser.getId(), likeId);
}

@GetMapping("/main")
public List<GatheringPopularResponse> findPopularGathering(){
return gatheringService.gatheringPopular(getUserFromContext());
}

private Optional<User> getUserFromContext() {
User user = null;
try {
user = UserUtils.getContextUser();
} catch (Exception e) {
log.info("Current user is not logged in");
}

return Optional.ofNullable(user);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ public record GatheringDetailsResponse(
String contactUrl,
String title,
String content,
boolean isLiked
Long hits,
boolean isLiked,
boolean isHits
) {

public static GatheringDetailsResponse toDto(Gathering gathering, Long likeCounts, boolean isLiked) {
public static GatheringDetailsResponse toDto(Gathering gathering, Long likeCounts, Long hits,boolean isLiked, boolean isHits) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String createTime = gathering.getCreateAt().format(dateTimeFormatter);

Expand Down Expand Up @@ -57,10 +59,13 @@ public static GatheringDetailsResponse toDto(Gathering gathering, Long likeCount
gathering.getUrl(),
gathering.getTitle(),
gathering.getContent(),
isLiked
hits,
isLiked,
isHits
);
}


private static List<String> gatheringPositions(Gathering gathering) {

if(gathering.getPositions() != null && !gathering.getPositions().isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.palettee.gathering.controller.dto.Response;

import com.palettee.gathering.domain.Gathering;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
@NoArgsConstructor
public class GatheringPopularResponse {
private Long gatheringId;
private Long userId;
private String sort;
private int person;
private String subject;
private String title;
private String deadLine;
private String username;
private List<String> tags;
private List<String> positions;
private Double score;
private boolean isLiked;

public GatheringPopularResponse(Long gatheringId, String sort, Long userId, String subject, int person, String title, List<String> positions, Double score, String deadLine, String username, List<String> tags) {
this.gatheringId = gatheringId;
this.sort = sort;
this.userId = userId;
this.subject = subject;
this.person = person;
this.title = title;
this.positions = positions;
this.score = score;
this.deadLine = deadLine;
this.username = username;
this.tags = tags;
}

public static GatheringPopularResponse toDto(Gathering gathering, Double score) {

String deadLine = gathering.getDeadLine().toString();

List<String> gatheringTagList = checkGatheringTag(gathering);

List<String> positions = gatheringPositions(gathering);


return new GatheringPopularResponse(
gathering.getId(),
gathering.getSort().getSort(),
gathering.getUser().getId(),
gathering.getSubject().getSubject(),
gathering.getPersonnel(),
gathering.getTitle(),
positions,
score,
deadLine,
gathering.getUser().getName(),
gatheringTagList
);
}


private static List<String> checkGatheringTag(Gathering gathering) {
if(gathering.getGatheringTagList() != null && !gathering.getGatheringTagList().isEmpty()){
return gathering.getGatheringTagList().stream()
.map(gatheringTag -> gathering.getContent()).toList();
}
return null;
}

private static List<String> gatheringPositions(Gathering gathering) {

if(gathering.getPositions() != null && !gathering.getPositions().isEmpty()) {
List<String> positionList = gathering.getPositions()
.stream()
.map(position -> position.getPositionContent().getPosition())
.toList();
return positionList;
}
return null;
}

}
3 changes: 3 additions & 0 deletions src/main/java/com/palettee/gathering/domain/Gathering.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ public class Gathering extends BaseEntity {

private int personnel; // 모집 인원

private int hits;

@Enumerated(EnumType.STRING)
private Status status; // 현재 모집 상태

Expand Down Expand Up @@ -80,6 +82,7 @@ public Gathering(
List<GatheringTag> gatheringTagList,
List<GatheringImage> gatheringImages
) {
this.hits = 0;
this.sort = sort;
this.subject = subject;
this.period = period;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import com.palettee.gathering.domain.Gathering;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Optional;

public interface GatheringRepository extends JpaRepository<Gathering, Long>, GatheringRepositoryCustom {
Expand All @@ -20,4 +22,14 @@ public interface GatheringRepository extends JpaRepository<Gathering, Long>, Gat
@Query("update Gathering g set g.status = 'EXPIRED' where g.status = 'ONGOING' AND g.deadLine < CURRENT_TIMESTAMP")
void updateStatusExpired();

@Modifying(clearAutomatically = true)
@Query("update Gathering g set g.hits = g.hits + :count where g.id = :gatheringId")
void incrementHits(@Param("count") Long count , @Param("gatheringId") Long gatheringId);

@Query("select g from Gathering g join fetch g.user where g.id in :gatheringIds")
List<Gathering> findByUserIds(@Param("gatheringIds") List<Long> gatheringIds);




}
76 changes: 63 additions & 13 deletions src/main/java/com/palettee/gathering/service/GatheringService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.palettee.gathering.controller.dto.Request.GatheringCommonRequest;
import com.palettee.gathering.controller.dto.Response.GatheringCommonResponse;
import com.palettee.gathering.controller.dto.Response.GatheringDetailsResponse;
import com.palettee.gathering.controller.dto.Response.GatheringPopularResponse;
import com.palettee.gathering.domain.Contact;
import com.palettee.gathering.domain.Gathering;
import com.palettee.gathering.domain.Sort;
Expand All @@ -24,10 +25,14 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
@RequiredArgsConstructor
Expand All @@ -45,6 +50,8 @@ public class GatheringService {

private final RedisService redisService;

private final RedisTemplate<String, Object> redisTemplateForTarget;


@Transactional
public GatheringCommonResponse createGathering(GatheringCommonRequest request, User user) {
Expand Down Expand Up @@ -97,24 +104,14 @@ public CustomSliceResponse findAll(
public GatheringDetailsResponse findByDetails(Long gatheringId, Long userId) {
Gathering gathering = getFetchGathering(gatheringId);

boolean isHits = redisService.viewCount(gatheringId, userId, "gathering");

long likeCounts = calculateLikeCounts(gatheringId);

return GatheringDetailsResponse.toDto(gathering, likeCounts, isLikedUserGathering(gatheringId, userId));
return GatheringDetailsResponse.toDto(gathering, likeCounts, calculateHitsCount(gathering),isLikedUserGathering(gatheringId, userId),isHits);
}



private long calculateLikeCounts(Long gatheringId) {
long likeCounts = likeRepository.countByTargetId(gatheringId);

Long count = redisService.likeCountInRedis("gathering", gatheringId);

if(count == null){
count = 0L;
}
return likeCounts + count;
}

@Transactional
public GatheringCommonResponse updateGathering(Long gatheringId, GatheringCommonRequest request, User user) {

Expand Down Expand Up @@ -187,12 +184,49 @@ public CustomSliceResponse findLikeList(
return gatheringRepository.PageFindLikeGathering(pageable, userId, likeId);
}

public List<GatheringPopularResponse> gatheringPopular(Optional<User> user){
String zSetKey = "gathering_Ranking";
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Const 이용해서 전역 변수로 처리하면 좋을 것 같아요!!


List<GatheringPopularResponse> listFromRedis = getListFromRedis(zSetKey);

user.ifPresent(u -> {
List<Long> longs = listFromRedis
.stream()
.map(GatheringPopularResponse::getGatheringId)
.toList();

Set<Long> gatheringIds = likeRepository.findByTargetIdAndTarget(user.get().getId(),LikeType.GATHERING ,longs);

if (gatheringIds.isEmpty()) {
log.info("유저가 누른 아이디가 없음");
}

listFromRedis.forEach(response -> response.setLiked(gatheringIds.contains(response.getGatheringId())));
});
return listFromRedis;
}


@SuppressWarnings("unchecked")
public List<GatheringPopularResponse> getListFromRedis(String zSetKey) {
Object result = redisTemplateForTarget.opsForValue().get(zSetKey);
if (result instanceof List) {
return (List<GatheringPopularResponse>) result; // List<PortFolioPopularResponse>로 캐스팅
}
return Collections.emptyList(); // 빈 리스트 반환
}





public Gathering getGathering(Long gatheringId){
return gatheringRepository.findById(gatheringId)
.orElseThrow(() -> GatheringNotFoundException.EXCEPTION);

}


private Gathering getFetchGathering(Long gatheringId) {
return gatheringRepository.findByGatheringId(gatheringId)
.orElseThrow(() -> GatheringNotFoundException.EXCEPTION);
Expand Down Expand Up @@ -234,6 +268,22 @@ private void deleteImages(Gathering gathering) {
}
}

private long calculateLikeCounts(Long gatheringId) {
long likeCounts = likeRepository.countByTargetId(gatheringId);

Long count = redisService.likeCountInRedis("gathering", gatheringId);

return likeCounts + count;
}

private long calculateHitsCount(Gathering gathering){
long dbCount = gathering.getHits();

Long redisInViewCount = redisService.viewCountInRedis("gathering", gathering.getId());

return dbCount + redisInViewCount;
}



}
61 changes: 0 additions & 61 deletions src/main/java/com/palettee/global/cache/MemoryCache.java

This file was deleted.

Loading
Loading