Design Objectives
service→ cache → Database
Initial query data from the database, query again from the cache
Has the deletion, the cache invalidation project structure
Main concerns: Service, Jpadao, entity several source packages and test packages
Configuration files-JPA files under Resources and-redis files in cache directory
Build statement in \showcase\src\test\resources\init-table-user.sql
Log configuration in \showcase\src\test\resources\logback-test.xml Spring Data JPA Complete DAO authoring Dependency Management
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId> spring-data-jpa</artifactid>
<version>1.11.7.RELEASE</version>
</dependency>
<!--hibernate jpa-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
< artifactid>javax.el-api</artifactid>
<version>2.2.4</version>
</dependency >
Of course, there are other dependencies, such as the H2 database to be used below, the spring context, and so on, when the reader runs the test case, what kind of package is needed. entity class Org.lanqiao.showcase.entity.User
@Entity
@Table (name = "T_user") public
class user implements serializable{
private Integer ID;
Private String username;
private String password;
Private Integer status;
Private Integer Teamid;
@Id
@GeneratedValue (Strategy =generationtype.auto) public
Integer GetId () {return
Id;
}
@Column (name= "team_id") public
Integer Getteamid () {return
teamid;
}
The rest slightly
Sql:init-table-user.sql
CREATE TABLE IF not EXISTS t_user (
ID int. not NULL auto_increment,
username VARCHAR (MB),
password VARCHAR (m),
status int,
team_id int,
PRIMARY KEY (' id ')
);
INSERT into T_user (username, password, status,team_id) VALUES (' AAA ', ' AAA ', 1,1);
INSERT into T_user (username, password, status,team_id) VALUES (' BBB ', ' AAA ', 1,1);
INSERT into T_user (username, password, status,team_id) VALUES (' CCC ', ' AAA ', 1,2);
INSERT into T_user (username, password, status,team_id) VALUES (' ddd ', ' aaa ', 1,2);
CREATE TABLE t_team (
ID INT auto_increment,
name VARCHAR (),
PRIMARY KEY (' id ')
);
INSERT into T_team (name) VALUES (' Black Mountain Old Demon ');
INSERT into T_team (name) VALUES (' Tianshan Child Mother ');
Spring XML Applicationcontext-jpa.xml
<!--Jpa Entity Manager configuration Entitymanager is a crud api--> <bean id= "Entitymanagerfactory" class= Rk.orm.jpa.LocalContainerEntityManagerFactoryBean "> <property name=" dataSource "ref=" DataSource "/> <PR Operty name= "Jpavendoradapter" ref= "Hibernatejpavendoradapter"/> <!--scan entity @entity--> <property "PA
Ckagestoscan "value=" org.lanqiao.showcase.entity "/> <property name=" jpaproperties "> <props> <!--naming convention my_name->myname--> <prop key= "Hibernate.ejb.naming_strategy" >org.hibernate.cfg.improv ednamingstrategy</prop> </props> </property> </bean> <bean id= "Hibernatejpavendo Radapter "class=" Org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter > <!--set dialect--> <property Name= "Databaseplatform" value= "Org.hibernate.dialect.H2Dialect"/> </bean> <!--Spring Data JPA configuration Find and assemble Dao--> <jpa:reposItories base-package= "Org.lanqiao.showcase.jpadao" transaction-manager-ref= "TransactionManager" entity-manager-factory-ref= "Entitymanagerfactory"/> <!--JPA transaction configuration--> <bean id= "transaction Manager "class=" Org.springframework.orm.jpa.JpaTransactionManager > <property name= "entitymanagerfactory" ref= "Entitymanagerfactory"/> </bean> <!--use annotation to define transactions--> <tx:annotation-driven transaction- Manager= "TransactionManager" proxy-target-class= "true"/> <jdbc:embedded-database id= "DataSource" type= "H2" > <jdbc:script location= "classpath:init-table-user.sql"/> </jdbc:embedded-database> <bean id= " UserService "class=" Org.lanqiao.showcase.service.UserService "/>
DAO's Writing Org.lanqiao.showcase.jpadao.UserDao
Import Org.lanqiao.showcase.entity.User;
Import org.springframework.data.repository.CrudRepository;
Public interface Userdao extends crudrepository<user,integer> {
}
Unit Test Org.lanqiao.showcase.jpadao.UserDaoTest
Package Org.lanqiao.showcase.jpadao;
Import Org.lanqiao.showcase.entity.User;
Import Org.junit.Before;
Import Org.junit.Test;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.test.context.ContextConfiguration;
Import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
Import Org.web2017.test.data.RandomData;
Import static org.assertj.core.api.Assertions.assertThat; @ContextConfiguration ("Classpath:applicationcontext-jpa.xml") public class Userdaotest extends
abstracttransactionaljunit4springcontexttests {@Autowired private Userdao Userdao;
@Test public void Testfindall () {save ();
Initialize 4 and add a Assertthat (Userdao.findall (). iterator ()). Hassize (5);
private void Save () {Final user entity = new user ();
Entity.setusername (Randomdata.randomname ("username"));
Entity.setpassword (Randomdata.randomname ("password"));
Userdao.save (entity); }
}
by the way, put down the Logback-test.xml (test/resources directory)
To view SQL printing:
<?xml version= "1.0" encoding= "UTF-8"?> <configuration> <appender name= "console" class= "Ch.qos.logback . Core. Consoleappender "> <encoder> <pattern>%date{hh:mm:ss.
SSS} [%thread]%-5level%logger{36}-%msg%n </pattern> </encoder> </appender> <appender name= "Rollingfile" class= "Ch.qos.logback.core.rolling.RollingFileAppender" > <FILE&G t;/tmp/logs/fullstack.log</file> <rollingpolicy class= " Ch.qos.logback.core.rolling.TimeBasedRollingPolicy "> <filenamepattern>/tmp/logs/fullstack.%d{yyyy-mm- Dd}.log </fileNamePattern> </rollingPolicy> <encoder> <patter N>%date{hh:mm:ss.
SSS} [%thread]%-5level%logger{36}-%msg%n </pattern> </encoder> </appender> <!--project Default level--> <logger name= "Org.lanqiao level=" DebUG "/> <logger name=" org.web2017 level= "Debug"/> <logger name= "Org.hibernate.SQL" level= "Debug"/>
; <root level= "Warn" > <appender-ref ref= "console"/> <!--production environment Cancel downlink comment <appender-ref ref= "Rollingfile" level= "error"/>--> </root> </configuration>
Mainly this line <logger name= "Org.hibernate.SQL" level= "Debug"/> Summary
Unit tests can run through, indicating that access to the persistent layer database is not a problem Spring cache consolidation Redis completes the service layer cache Redis connection Information cache/redis-config.properties
# Redis Settings
# server IP
redis.host=your_redis_ip
# server Port
redis.port=63799
# Server Pass
Redis.pass=your_redis_secret
# use Dbindex
redis.database=0
# Control a pool up to how many states are idle (idle) Jedis instance
redis.maxidle=300
# represents the maximum wait time if the borrow (introduced) a Jedis instance, if more than the wait time (milliseconds), The Jedisconnectionexception redis.maxwait=3000 # is thrown directly if the
validate operation is done in advance borrow a Jedis instance; The resulting Jedis instances are available
redis.testonborrow=true
Configure Rediscachemanager and turn on cache annotation driver: Cache/applicationcontext-redis.xml
<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:cache= "Http://www.springframework.org/schema/cache" xmlns:p= "http://www.springframework.org/schema/p" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:c= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/C" xsi:schemalocation= "Http://www.springframework.org/schema/beans http:/ /www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/cache http:// Www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context http:// Www.springframework.org/schema/context/spring-context.xsd "> <context:property-placeholder location=" Classpath:cache/redis-config.properties "/> <!--enable cache annotations, this is necessary, otherwise the annotation will not take effect, and it must be declared in the Spring master configuration file- > <cache:annotation-driven cache-manager= "Rediscachemanager"/> <!--REdis related configuration--> <bean id= "Poolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "Maxidle" "Value=" ${redis.maxidle} "/> <property name=" Maxwaitmillis "value=" ${redis.maxwait} "/> <property name= ' Testonborrow ' value= ' ${redis.testonborrow} '/> </bean> <bean id= ' jedisconnectionfactory ' class= ' O Rg.springframework.data.redis.connection.jedis.JedisConnectionFactory "P:host-name=" ${redis.host} "p:port=" ${ Redis.port} "p:password=" ${redis.pass} "p:pool-config-ref=" Poolconfig "/> <bean id=" redisTemplate "class=" Org.springframework.data.redis.core.RedisTemplate "> <property name=" connectionfactory "ref=" Jedisconnectionfactory "/> <property name=" Keyserializer "> <bean class=" org.springframework.data.red Is.serializer.StringRedisSerializer "/> </property> <property name=" ValueSerializer "> <bea n class= "Org.springframework.data.redis.serializeR.jdkserializationredisserializer "/> </property> </bean> <!--Spring's own cache manager, where the cache location name is defined, that is, the
Value--> <bean id= "Rediscachemanager" class= "Org.springframework.data.redis.cache.RedisCacheManager" c:redisoperations-ref= "Redistemplate" p:useprefix= "true" > <property name= "Cachenames" >
;list> <value>userCache</value> <value>teamCache</value> </list> </property> <property name= "Cacheprefix" > <bean class= "Org.springframework.data.redis.cache.Def" Aultrediscacheprefix "/> </property> </bean> </beans>
This online can find, need to explain: redistemplate in order to facilitate to Redis server to check data, it is best to set the key serialization to string serialization:
<property name= "Keyserializer" >
<bean class= " Org.springframework.data.redis.serializer.StringRedisSerializer "/>
</property>
The value serialization is serialized with the JDK, so our entity classes implement the Serializable interface writing service to complete simple logic and use the spring @Cache xxx annotation:
Package org.lanqiao.showcase.service;
Import Org.lanqiao.showcase.entity.User;
Import Org.lanqiao.showcase.jpadao.UserDao;
Import Org.springframework.beans.factory