Spring Boot Cache Combat EhCache

Source: Internet
Author: User

Spring boot uses simplecacheconfiguration by default, that is, using Concurrentmapcachemanager to implement caching. But it's easy to switch to another cache implementation. Pom File

Introducing the appropriate jar package in the POM

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactid >spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId> Org.springframework.boot</groupid> <artifactId>spring-boot-starter-data-jpa</artifactId> </ dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java< /artifactid> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artif actid>commons-dbcp2</artifactid> </dependency> <dependency> <groupId> Org.springframework.boot</groupid> <artifactId>spring-boot-starter-cache</artifactId> </ dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactid>ehcache</ Artifactid> </dependency> </dependencies>
configuration file

The configuration files required by Ehcache are simply placed under the classpath and Spring boot is automatically scanned.

<?xml version= "1.0" encoding= "UTF-8"?>
<ehcache> <cache name= "People" maxelementsinmemory= "
    1000 "/>
</ehcache>

You can also specify the location of the Ehcache configuration file by configuring it in the Application.properties file, such as:

spring.cache.ehcache.config= #  Ehcache configuration file Address

Spring boot automatically configures the Ehcachecachemannager bean for us. Key Service

Package Com.xiaolyuh.service.impl;
Import Com.xiaolyuh.entity.Person;
Import Com.xiaolyuh.repository.PersonRepository;
Import Com.xiaolyuh.service.PersonService;
Import org.springframework.beans.factory.annotation.Autowired;
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 Personserviceimpl implements Personservice {@Autowired personrepository personrepository;  @Override @CachePut (value = "people", key = "#person. ID") Public person Save (person person) {person P
        = Personrepository.save (person);
        SYSTEM.OUT.PRINTLN ("For ID, key is:" + p.getid () + "data cache");
    return p; @Override @CacheEvict (value = "people")//2 public void remove (Long ID) {System.out.println ("Delete ID,
        Key is "+ ID +" "data cache"); This does not do the actual delete operation} @Override @CacheAble (value = "people", key = "#person. ID")//3 public person findone (person person) {Person P = Personreposito
        Ry.findone (Person.getid ());
        SYSTEM.OUT.PRINTLN ("For ID, key is:" + p.getid () + "data cache");
    return p; }
}
Controller
Package Com.xiaolyuh.controller;
Import Com.xiaolyuh.entity.Person;
Import Com.xiaolyuh.service.PersonService;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.cache.CacheManager;
Import Org.springframework.web.bind.annotation.RequestBody;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.RestController;

    @RestController public class Cachecontroller {@Autowired personservice personservice;

    @Autowired CacheManager CacheManager;
        @RequestMapping ("/put") public long put (@RequestBody person person) {Person P = personservice.save (person);
    return P.getid (); @RequestMapping ("/able") public person cacheable {System.out.println (cachemanager.tostr
        ing ());
    return Personservice.findone (person);
        @RequestMapping ("/evit") public String Evit (Long id) {personservice.remove (ID); RetUrn "OK"; }

}
Start class
@SpringBootApplication
@EnableCaching//Open cache, need to display the specified public
class Springbootstudentcacheapplication {

	public static void Main (string[] args) {
		springapplication.run (springbootstudentcacheapplication.class, args);
}
Test Class
Package com.xiaolyuh;
Import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
Import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

Import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
Import Java.util.HashMap;

Import Java.util.Map;
Import Org.junit.Before;
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.http.MediaType;
Import Org.springframework.test.context.junit4.SpringRunner;
Import ORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;
Import Org.springframework.test.web.servlet.MvcResult;
Import Org.springframework.test.web.servlet.setup.MockMvcBuilders;

Import Org.springframework.web.context.WebApplicationContext;

Import Net.minidev.json.JSONObject; @RunWith (Springrunner.class) @SpringBootTest public class SPRINGBOOTSTUDENTCACheapplicationtests {@Test public void Contextloads () {} private MOCKMVC MOCKMVC;//Simulate an MVC object, through MOCKMVCB

    Uilders.webappcontextsetup (THIS.WAC). Build () initialized. @Autowired private Webapplicationcontext WAC;    Inject Webapplicationcontext//@Autowired//Private mockhttpsession session;//inject simulated HTTP session//// @Autowired//Private mockhttpservletrequest request;//inject the simulated HTTP request\ @Before//Initialize the work pub before the test starts
    LIC void Setup () {This.mockmvc = Mockmvcbuilders.webappcontextsetup (THIS.WAC). build (); @Test public void testable () throws Exception {for (int i = 0; i < 2; i++) {Mvcresult result = Mockmvc.perform (post ("/able"). PARAM ("id", "2")). Andexpect (Status (). IsOk ())//simulate sending GE to Testrest
                    T request. Andexpect (Content (). ContentType (Mediatype.application_json_utf8))//Expected return value of the media type Text/plain; Charset=utf-8. Andreturn ();/Returns the results of the execution request System.out.println (Result.getresponse (). getcontentasstring ()); }
    }

}
Print Log

From the above you can see that the first walk is the database, the second walk is the cache

Source: https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases

Spring-boot-student-cache-ehcache Engineering



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.