1. Caching

Source: Internet
Author: User

CacheManager: Manage various components;

Cache: The interface that actually operates the buffer;

@Cacheable: cacheable, if labeled in a method, then the return result of this method will be cached;

@CacheEvict: Empty the cache, when a user is deleted, the deleted method is marked above, then the user's cache will be deleted;

@CachePut: Update the cache, update a user, labeling in the updated method, the characteristics of this method of prestige, ensure that the method will be called, and the results will be cached;

@EnableCaching: Enable annotation-based caching;

Keygenerator: Key generation strategy when caching data;

Serialize: The cached data is the value serialization policy;

1. Basic Environment Construction

Import: Web, Cache, MySQL, MyBatis module;

Create a new Spring_cache database, import the following SQL file and import it directly: (Note:linux mysql default is to distinguish table name casing )

/*Navicat MySQL Data transfersource Server: Local source server Version:50528source host:127.0.0.1:33         06Source database:springboot_cachetarget Server type:mysqltarget server Version:50528file Encoding : 65001date:2018-04-27 14:54:04*/SETForeign_key_checks=0;-- ------------------------------Table Structure for department-- ----------------------------DROP TABLE IF EXISTS' department ';CREATE TABLE' Department ' (' ID ')int( One) not NULLauto_increment, ' Departmentname 'varchar(255)DEFAULT NULL,  PRIMARY KEY(' id ')) ENGINE=InnoDBDEFAULTCHARSET=UTF8;-- ------------------------------Table structure for employee-- ----------------------------DROP TABLE IF EXISTS' employee ';CREATE TABLE' employee ' (' ID ' )int( One) not NULLauto_increment, ' LastName 'varchar(255)DEFAULT NULL, ' email 'varchar(255)DEFAULT NULL, ' Gender 'int(2)DEFAULT NULL, ' d_id 'int( One)DEFAULT NULL,  PRIMARY KEY(' id ')) ENGINE=InnoDBDEFAULTCHARSET=UTF8;
View Code

Application.properties:

View Code

Bean:

 PackageCom.ning.cache.bean; Public classDepartment {PrivateInteger ID; PrivateString Departmentname;  PublicDepartment () {Super(); //TODO auto-generated Constructor stub    }     PublicDepartment (Integer ID, String departmentname) {Super();  This. ID =ID;  This. Departmentname =Departmentname; }     PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString Getdepartmentname () {returnDepartmentname; }     Public voidsetdepartmentname (String departmentname) { This. Departmentname =Departmentname; } @Override PublicString toString () {return"Department [id=" + ID + ", departmentname=" + Departmentname + "]"; }                }
View Code
 PackageCom.ning.cache.bean; Public classEmployee {PrivateInteger ID; PrivateString LastName; PrivateString Email; PrivateInteger gender;//Sex 1 Male 0 female    PrivateInteger did;  PublicEmployee () {Super(); }         PublicEmployee (integer ID, string lastName, string email, integer gender, Integer did) {Super();  This. ID =ID;  This. LastName =LastName;  This. email =email;  This. Gender =gender;  This. did =Did ; }         PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString Getlastname () {returnLastName; }     Public voidsetlastname (String lastName) { This. LastName =LastName; }     PublicString Getemail () {returnemail; }     Public voidsetemail (String email) { This. email =email; }     PublicInteger Getgender () {returngender; }     Public voidSetgender (Integer gender) { This. Gender =gender; }     PublicInteger Getdid () {returnDid ; }     Public voidSetdid (Integer did) { This. did =Did ; } @Override PublicString toString () {return"Employee [id=" + ID + ", lastname=" + LastName + ", email=" + email + ", gender=" + Gender + ", did=" + DI D + "]"; }        }
View Code

The Mapper interface is as follows:

 PackageCom.ning.cache.mapper;ImportCom.ning.cache.bean.Employee;Importorg.apache.ibatis.annotations.*; @Mapper Public Interfaceemployeemapper {@Select ("SELECT * from Employee where Id=#{id}")     PublicEmployee Getempbyid (Integer ID); @Update ("Update employee set Lastname=#{lastname},email=#{email},gender=#{gender},d_id=#{did} where Id=#{id}")     Public voidupdateemp (employee employee); @Delete ("Delete from employee WHERE id = #{id}")     Public voidDeleteempbyid (Integer ID); @Insert ("INSERT into employee (LASTNAME,EMAIL,GENDER,D_ID) VALUES (#{lastname},#{email},#{gender},#{did})")     Public voidInsertemployee (employee employee);}
View Code

The service is as follows:

 PackageCom.ning.cache.service;ImportCom.ning.cache.bean.Employee;ImportCom.ning.cache.mapper.EmployeeMapper;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service; @Service Public classEmpservice {@Autowired employeemapper employeemapper;  PublicEmployee getemp (Integer ID) {Employee EMP=Employeemapper.getempbyid (ID);        SYSTEM.OUT.PRINTLN (EMP); returnEMP; }}
View Code

The controller is as follows:

 PackageCom.ning.cache.controller;ImportCom.ning.cache.bean.Employee;ImportCom.ning.cache.service.EmpService;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.GetMapping;Importorg.springframework.web.bind.annotation.PathVariable;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController; @RestController//synthetic annotations of @RequestMapping and @controller Public classEmpcontroller {@Autowired empservice empservice; @GetMapping ("/emp/{id}")//gets the ID parameter of the GET request     PublicEmployee getemp (@PathVariable ("id") Integer ID) {//Remove the value of the ID placeholder from the PATH variableEmployee emp =empservice.getemp (ID); returnEMP; }}
View Code

The test classes are as follows:

 PackageCom.ning.cache;ImportCom.ning.cache.bean.Employee;ImportCom.ning.cache.mapper.EmployeeMapper;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.boot.test.context.SpringBootTest;ImportOrg.springframework.test.context.junit4.SpringRunner; the @RunWith (Springrunner.class) @SpringBootTest Public classspringboot01cacheapplicationtests {@Autowired employeemapper employeemapper; @Test Public voidcontextloads () {Employee emp= Employeemapper.getempbyid (1); System.out.println ("EMP =" +EMP); }}
View Code

Remarks: Injected into the project

@Autowired
Employeemapper Employeemapper;

When the report does not have this bean this is OK because the project has no reason to detect the bean.

Project structure

1. Caching

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.