In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how SpringBoot uses Redis cache". In daily operation, I believe many people have doubts about how SpringBoot uses Redis cache. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how SpringBoot uses Redis cache". Next, please follow the editor to study!
1 redis is installed on linux
Install docker
Yum install docker
2) enable docker
Service docker start
2 install Redis
You can go to this website to find out how to install https://hub.docker.com
Turn on redis
3 create a springBoot project (I won't repeat the details)
Pom.xml file
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.6.RELEASE com.maospring-cache0.0.1-SNAPSHOTspring-cacheDemo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-jdbc Org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.0.1 mysql mysql-connector-java 5.1.47 runtime org.springframework.boot spring -boot-starter-test test org.springframework.boot spring-boot-maven-plugin
4 provide an entity class / / this file is from Shang School
Public class Employee implements Serializable
Private Integer id;private String lastName;private String email;private Integer gender; / / Sex 1 male 0 female private Integer dId
. (abbreviated)
}
Customers of 5 redis ask to install it themselves.
For relevant knowledge, please go to this website to learn http://www.redis.cn. There are many cases in it.
6 configuration property application.properties
Spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring_cache
Spring.datasource.username=root
Spring.datasource.password=123456
Spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# start hump nomenclature
Mybatis.configuration.map-underscore-to-camel-case=true
Logging.level.mao.springcache.mapper=debug
# since the redis I installed doesn't have a password, just give me the host address
Spring.redis.host=192.168.1.139
7 to test the cache of Redis, first take a look at how the source code is written
Public class SpringCacheApplicationTests {
/ / Operation key-value pair, jdk default serialization mechanism @ AutowiredRedisTemplate redisTemplate;// operation string @ AutowiredStringRedisTemplate stringRedisTemplate;@AutowiredRedisTemplate redisTemplate1; [@ Test] (https://my.oschina.net/azibug)public void test1 () {/ / stringRedisTemplate.opsForValue () .append ("hello", "hello"); System.out.println (stringRedisTemplate.opsForValue () .get ("hello")) } [@ Test] (https://my.oschina.net/azibug)public void test2 () {Employee employee = employeeMapper.getEmployee (1); redisTemplate.opsForValue () .set ("emp-01", employee);} @ Testpublic void contextLoads () {Employee employee = employeeMapper.getEmployee (1); System.out.println (employee.toString ());}
}
The above test1 test results:
The above test2 test results:
Next, we solve the ugly problem above: we rewrite RedisTemplate and we want the cache to view it as json.
@ Configuration
Public class myredis {
@ Beanpublic RedisTemplate redisTemplate (RedisConnectionFactory redisConnectionFactory) {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (redisConnectionFactory); Jackson2JsonRedisSerializer ser = new Jackson2JsonRedisSerializer (Employee.class); template.setDefaultSerializer (ser); return template;}}
The principle has been shown in the previous picture.
The following picture explains the sentence haul template.setDefaultSerializer (ser).
Results of the retest
8 then we will talk about the use of / / EmployeeService classes in spring projects
@ Service
Public class EmployeeService {
@ AutowiredEmployeeMapper employeeMapper / / cache the result of the method, request the same data later, and get it directly from the cache. There is no need to call the method / / CacheManner to manage multiple Cache components. For the real CRUD component of the cache, each cache group has its own unique name / several attributes. Specify the cache name key, and you can specify @ param id@Cacheable (cacheNames = {"emp"}) public Employee getEmp (Integer id) {System.out.println ("query" + id+ "employee"). Employee employee = employeeMapper.getEmployee (id); return employee;} / / achieves the goal of synchronously updating the cache. The cache key should be the same as the slow key @ CachePut (cacheNames = "emp", key = "# cache") public Employee updateEmp (Employee employee) {employeeMapper.updateEmp (employee); return employee } @ CacheEvict (value = "emp", key = "# id") public void deleteEmp (Integer id) {System.out.println ("deleteEMp" + id); public Employee getEmployeeByLastName (String lastName) {return employeeMapper.getEmpByLastName (lastName);}
}
EmployeeMapper code
Public interface EmployeeMapper {
@ Select ("select * from employee where id=# {id}") public Employee getEmployee (Integer id); @ Update ("update employee set lastName=# {lastName}, email=# {email}, gender=# {gender}, d_id=# {dId} where id=# {id}") public void updateEmp (Employee employee); @ Delete ("delete * from employee where id=# {id}") public void deleteEmpById (Integer id) Insert ("insert into employee (lastName,email,gender,d_id) values (# {lastName}, # {email}, # {gender}, # {dId})") public void insertEmpployee (Employee employee); @ Select ("select * from employee where lastName=# {lastName}") public Employee getEmpByLastName (String name)
}
EmployeeController.java
@ RestController
Public class EmployeeController {
@ AutowiredEmployeeService employeeService;@RequestMapping ("/ emp/ {id}") public Employee getEmployee (@ PathVariable ("id") Integer id) {Employee employee=employeeService.getEmp (id); return employee;} @ GetMapping ("/ emp") public Employee updateEmp (Employee employee) {System.out.println ("method calls for employee updates"); Employee employee1 = employeeService.updateEmp (employee); return employee1 } @ GetMapping ("/ delete") public String deleteEmp (Integer id) {System.out.println ("delete information about an employee"); return "delete employee";} @ RequestMapping ("/ emps/ {lastName}") public Employee getByLastName (@ PathVariable ("lastName") String lastName) {return employeeService.getEmployeeByLastName (lastName);}
}
Attention to the configuration of application classes
The following is what I most want to write. I couldn't write the video of Shang School at that time. Because of the different version I used, I used 2.xxx.
Here is the RedisCacheManager I configured
@ Configuration
Public class myredis {
@ Bean
Public RedisCacheManager redisCacheManager (RedisConnectionFactory redisConnectionFactory) {
Jackson2JsonRedisSerializer ser = new Jackson2JsonRedisSerializer (Employee.class); RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig () .serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (ser)); RedisCacheManager cacheManager = RedisCacheManager.builder (redisConnectionFactory) .cacheDefaults (config). Build (); return cacheManager
}
} this way of writing is obviously different from 1.xx.
The following is the 2.xx source code
The following picture explains this sentence.
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig ()
.serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (ser))
Test result
At this point, the study on "how SpringBoot uses Redis caching" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.