가자공부하러!

EHCache 설정과 활용(Spring Boot 2.1.8) 본문

공부/Spring Boot

EHCache 설정과 활용(Spring Boot 2.1.8)

오피스엑소더스 2019. 9. 19. 19:09

참고 : https://tram-devlog.tistory.com/entry/Spring-EhCache-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0

참고 : https://jojoldu.tistory.com/57

참고 : https://055055.tistory.com/15

1. EHCache 적용


1. 개발환경

  > Spring Boot 2.1.8(maven, spring security)

  > JDK 1.8


2. 적용 순서

  > 디펜던시 추가(pom.xml) -> configuration 파일 작성 -> 테스트

  > 디펜던시 추가(pom.xml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- EHCache 관련 -->
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
<dependency>
    <!-- 캐시 관련 의존성(CacheManager 등)을 직접 추가하지 않기 위해 추가한 디펜던시 -->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>    
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
</dependency>
cs

  > configuration 파일 작성

- application.yml

1
2
3
4
#ehcache config
cache:
  ehcache:
    config: classpath:config/ehcache.xml
cs

- ehcache.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>
    <cache name="findByBestCategoryCache"
           maxEntriesLocalHeap="10000"
           maxEntriesLocalDisk="1000"
           eternal="false"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="300" timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>
cs

- CacheConfiguration.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.rhymes.app.config.cache;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
 
import lombok.extern.slf4j.Slf4j;
 
/**EHCache 활용을 위한 설정
 * @author minhj
 *
 */
@Slf4j
@Configuration
@EnableCaching
public class CacheConfiguration implements CommandLineRunner {
 
    @Autowired
    private CacheManager cacheManager;
    
 
    @Override
    public void run(String... args) throws Exception {
        // TODO Auto-generated method stub
        log.info("\n\n" + "=========================================================\n"
                + "Using cache manager: " + this.cacheManager.getClass().getName() + "\n"
                + "=========================================================\n\n");
    }
 
}
cs

- @SpringBootApplication(RhymesApplication.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.rhymes; 
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
 
@EnableCaching
@SpringBootApplication
public class RhymesApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(RhymesApplication.class, args);
    }
 
}
 
cs


  > 테스트 수행

- @Repository(MypagePointsDAOImpl.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.rhymes.app.member.dao.impl;
 
import java.util.List;
 
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
 
import com.rhymes.app.member.dao.MypagePointsDAO;
import com.rhymes.app.member.model.PointsPagingDTO;
import com.rhymes.app.member.model.mypage.MemberPointDTO;
 
@Repository
public class MypagePointsDAOImpl implements MypagePointsDAO {
 
    @Autowired
    private SqlSession sqlSession;
    
    private String ns = "points.";
    
    /**새 적립금 등록
     * @param mPDto
     * @return
     */
    @CacheEvict(value = "getAmountOfPointById", key = "#userid")
    @Override
    public int addNewPoint(MemberPointDTO mPDto) {
        return sqlSession.insert(ns + "addNewPoint", mPDto);
    }
    
    /**매개변수로 받은 ID가 갖는 적립금 중 유효한 적립금 총 합 리턴 
     * @param userid
     * @return
     */
    @Cacheable(key = "#userid", value = "getAmountOfPointById")
    @Override
    public int getAmountOfPointById(String userid) {
        // TODO Auto-generated method stub
        slowQuery(20000);
        return sqlSession.selectOne(ns + "getAmountOfPointById", userid);
    }
 
    // 빅쿼리를 돌린다는 가정
     private void slowQuery(long seconds) {
            try {
                Thread.sleep(seconds);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
    }
}
 
cs

- @Controller(MypageController.java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.rhymes.app.member.controller;
 
import java.net.URLDecoder;
import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.rhymes.app.member.model.MemberDTO;
import com.rhymes.app.member.model.P_MemberDTO;
import com.rhymes.app.member.model.PointsPagingDTO;
import com.rhymes.app.member.model.mypage.MemberCouponDTO;
import com.rhymes.app.member.model.mypage.MemberCouponDetailDTO;
import com.rhymes.app.member.model.mypage.MemberPointDTO;
import com.rhymes.app.member.service.MypageCouponService;
import com.rhymes.app.member.service.MypagePersonalService;
import com.rhymes.app.member.service.MypagePointsService;
 
import lombok.extern.slf4j.Slf4j;
 
 
@Slf4j
@EnableCaching
@Controller
@RequestMapping("/mypage/*")
public class MypageController {
 
    @Autowired
    private MypagePointsService mypagePointsService;
        
    /**적립금 현황 뷰를 보여주는 메소드
     * @param model
     * @param pcp
     * @param pageNum
     * @return
     */
    @GetMapping(value = "/points")
    public String showPoints(Model model, Principal pcp, @RequestParam(defaultValue = "1"int pageNum) {
        log.info("show points");
        
        long start = System.currentTimeMillis(); // 수행시간 측정        
        
        /* 선언부 */
        String userid = pcp.getName();    //세션에 로그인한 id정보
        String totalPoints = "0";    //유효한 적립금 총 액
        String expPoints = "0";    //만료 예정인 적립금 총 액
        int detailCount = 0;    //적립금 적립내역 총 개수        
        PointsPagingDTO pDto = null;    //페이징 DTO    
        List<MemberPointDTO> lst = null;    //적립금 세부내역 리스트
                
        try {
            /* DB통신 */
            detailCount = mypagePointsService.getCountOnConditions(userid);
            pDto = new PointsPagingDTO(pageNum, detailCount, userid);
            lst = mypagePointsService.getDetailsOnConditions(pDto);
            totalPoints = String.format("%,d", mypagePointsService.getAmountOfPointById(userid));
            expPoints = String.format("%,d", mypagePointsService.getAmountOfExpiredPointById(userid) );
        }catch (Exception e) {
            e.printStackTrace();
        }
        
        model.addAttribute("totalPoints", totalPoints);
        model.addAttribute("expPoints", expPoints);
        model.addAttribute("pointsList", lst);
        model.addAttribute("pDto", pDto);        
        
        long end = System.currentTimeMillis();
        
        log.info("Cache 수행시간 : "+ Long.toString(end-start));
        
        return "member/mypage/points"
    }
          
}
    
cs


  > 테스트 결과








Comments