First, preface
The select in the database is the most frequently used, and the basic is the same every time, and the update, delete, insert use frequency does not have a select high, and each time basically is different. In order to reduce the pressure of the database, it is necessary to use the cache for select, previously used Ehcache cache, but it has a very obvious disadvantage is that there is no IP, port, but the use of the path, not easy to play the role of shared cache. Therefore, using Redis as a cache is the best choice. Second, the code
GitHub Download This case code: https://github.com/larger5/SpringBootRedis.git
1. Entity
Package com.cun.entity;
Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.GeneratedValue;
Import Javax.persistence.Id;
Import javax.persistence.Table;
/**
* User entity
* @author linhongcun
*
*
/@Entity @Table (name = "user") Public
class user{< c13/> @Id
@GeneratedValue
private Integer Id;
@Column (length =)
private String userName;
@Column (length =)
private String password;
Public Integer getId () {
return ID;
}
public void SetId (Integer id) {
this.id = ID;
}
Public String GetUserName () {
return userName;
}
public void Setusername (String userName) {
this.username = userName;
}
Public String GetPassword () {
return password;
}
public void SetPassword (String password) {
this.password = password;
}
}
2. DAO interface
Package Com.cun.dao;
Import org.springframework.data.jpa.repository.JpaRepository;
Import Org.springframework.data.jpa.repository.JpaSpecificationExecutor;
Import Com.cun.entity.User;
/**
* User DAO interface
* @author linhongcun * */public
interface Userdao extends Jparepository<user, integer>,jpaspecificationexecutor<user>{
}
3. Service interface
Package com.cun.service;
Import java.util.List;
Import Com.cun.entity.User;
Public interface UserService {
/**
* Get all users
* @return
*
/list<user> getAllUsers ();
}
4. Service Implementation class
Package Com.cun.service.impl;
Import java.util.List;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.cache.annotation.CacheConfig;
Import org.springframework.cache.annotation.Cacheable;
Import Org.springframework.stereotype.Service;
Import Com.cun.dao.UserDao;
Import Com.cun.entity.User;
Import Com.cun.service.UserService;
@Service
@CacheConfig (cachenames = "UserService") Public
class Userserviceimpl implements UserService {
@Autowired
private Userdao Userdao;
/**
* 2, the method in the implementation class of the Service layer @ cache
*① Specify the cache key, the bean for wiselykeygenerator * */
@Override
@ cacheable (value = "GetAllUsers", keygenerator= "Wiselykeygenerator") public
list<user> getAllUsers () {
return Userdao.findall ();
}
}
5. Controller
Package Com.cun.controller;
Import java.util.List;
Import org.springframework.beans.factory.annotation.Autowired;
Import org.springframework.web.bind.annotation.GetMapping;
Import Org.springframework.web.bind.annotation.RestController;
Import Com.cun.entity.User;
Import Com.cun.service.UserService;
@RestController public
class Usercontroller {
@Autowired
private userservice userservice;
@GetMapping ("/all") public
list<user> getAllUsers () {
System.out.println ("Only the first time the SQL statement is printed");
return Userservice.getallusers ();
}
}
6. Redis Configuration
Package com.cun.conf;
Import Com.fasterxml.jackson.annotation.JsonAutoDetect;
Import Com.fasterxml.jackson.annotation.PropertyAccessor;
Import Com.fasterxml.jackson.databind.ObjectMapper;
Import Org.springframework.cache.CacheManager;
Import Org.springframework.cache.annotation.CachingConfigurerSupport;
Import org.springframework.cache.annotation.EnableCaching;
Import Org.springframework.cache.interceptor.KeyGenerator;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.data.redis.cache.RedisCacheManager;
Import Org.springframework.data.redis.connection.RedisConnectionFactory;
Import Org.springframework.data.redis.core.RedisTemplate;
Import Org.springframework.data.redis.core.StringRedisTemplate;
Import Org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
Import Java.lang.reflect.Method; /** * Redis Cache configuration class (generic) * @author linhongcun * */@Configuration @EnableCaching public CLASS Redisconfig extends Cachingconfigurersupport {/** * Cache object collection, the cache is saved in the form of Key-value.
When you do not specify a cached key, Springboot uses Simplekeygenerator to generate the key.
* @return */@Bean public keygenerator Wiselykeygenerator () {return new Keygenerator () { @Override public object generate (object target, Method method, Object ... params) {Stringbuil
Der SB = new StringBuilder ();
Sb.append (Target.getclass (). GetName ());
Sb.append (Method.getname ());
for (Object obj:params) {sb.append (obj.tostring ());
} return sb.tostring ();
}
}; } @Bean Public CacheManager CacheManager (@SuppressWarnings ("Rawtypes") Redistemplate redistemplate) {RET
Urn New Rediscachemanager (redistemplate); } @Bean public redistemplate<string, string> redistemplate (Redisconnectionfactory factory) {String ReDistemplate template = new Stringredistemplate (factory); @SuppressWarnings ({"Rawtypes", "Unchecked"}) Jackson2jsonredisserializer Jackson2jsonredisserializer = new Jacks
On2jsonredisserializer (Object.class);
Objectmapper om = new Objectmapper ();
Om.setvisibility (Propertyaccessor.all, JsonAutoDetect.Visibility.ANY);
Om.enabledefaulttyping (ObjectMapper.DefaultTyping.NON_FINAL);
Jackson2jsonredisserializer.setobjectmapper (OM);
Template.setvalueserializer (Jackson2jsonredisserializer);
Template.afterpropertiesset ();
return template;
}
}
7, Application.yml
Server:
port:80
context-path:/
Spring:
redis:
host:120.79.197.130
port:6378
DataSource:
driver-class-name:com.mysql.jdbc.driver
url:jdbc:mysql://localhost:3306/mybatis
Username:root
password:123
JPA:
hibernate:
ddl-auto:update
show-sql:true
8, Redis-springboot's Pom.xml
third, testing
1, the original Redis database, empty
2. Execute the query for the first time
① Browser
② Console
③redis Database
2. Second query
① Console