In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the Redis framework how to build SpringBoot2.X, the article is very detailed, has a certain reference value, interested friends must read it!
Use Spring Initializr to create a project web project
1 、 File → New → Project
2. Click Next as shown in the figure, and name Group and Artifact
3. After Next, as shown in the figure, check the required dependencies, and Spring Initializr will automatically import the required starter.
4. After the project is created successfully, the dependencies in the pom.xml file are as follows
4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE com.heny spring-boot-redis 0.0.1-SNAPSHOT spring-boot-redis Demo project for Spring Boot 1.8 Org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.1 Mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test Org.junit.vintage junit-vintage-engine Org.springframework.boot spring-boot-maven-plugin
5. Add the starter of redis in pom.xml file
Org.springframework.boot spring-boot-starter-data-redis
6. Create JavaBean to encapsulate database data, and you need to implement Serializable
Package com.henya.springboot.bean;import java.io.Serializable;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; public Employee () {super () } public Employee (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 } public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getLastName () {return lastName;} public void setLastName (String lastName) {this.lastName = lastName } public String getEmail () {return email;} public void setEmail (String email) {this.email = email;} public Integer getGender () {return gender;} public void setGender (Integer gender) {this.gender = gender } public Integer getdId () {return dId;} public void setdId (Integer dId) {this.dId = dId @ Override public String toString () {return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId=" + dId + "]";}}
Note:
You need to implement the Serializable interface when writing JavaBean objects, otherwise the following error will be reported:
Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException
7. Integrate the Mybatis operation database and configure the data source information in the application.properties configuration file
# serverTimezone is used to specify the time zone, otherwise an error will be reported that spring.datasource.url=jdbc:mysql://localhost:3306/cache?serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=123456# enables hump naming rules mybatis.configuration.map-underscore-to-camel-case=true# log level logging.level.com.henya.springboot.mapper=debug
8. Create a Mapper using the annotated version of Mybatis
Package com.henya.springboot.mapper;import com.henya.springboot.bean.Employee;import org.apache.ibatis.annotations.*;@Mapperpublic interface EmployeeMapper {@ Select ("SELECT * FROM employee WHERE id=# {id}") public Employee getEmpById (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 emlpoyee WHERE id=# {id}") public void delEmpById (Integer id); @ Insert ("INSERT INTO employee (lastName, email, gender, d_id) VALUES (# {lastName}, # {email}, # {gender}, # {dId})") public Employee insertEmp (Employee employee); @ Select ("SELECT * FROM employee WHERE lastName=# {lastName}") public Employee getEmpByLastName (String lastName);}
Note:
You need to use the @ MapperScan annotation to scan the interface where Mapper is located, just add it to the main program class. In addition, use @ EnableCaching to turn on caching.
@ MapperScan ("com.henya.springboot.mapper") @ SpringBootApplication@EnableCaching / / enable cache public class SpringBootRedisApplication {public static void main (String [] args) {SpringApplication.run (SpringBootRedisApplication.class, args);}}
9. Write Service classes to access the database or redis cache
Package com.henya.springboot.service;import com.henya.springboot.bean.Employee;import com.henya.springboot.mapper.EmployeeMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.*;import org.springframework.stereotype.Service;@CacheConfig (cacheNames = "emp") / / Public configuration of extraction cache @ Servicepublic class EmployeeService {@ Autowired EmployeeMapper employeeMapper / * @ param id * @ return * / @ Cacheable (cacheNames = {"emp"}, keyGenerator = "myKeyGenerator") public Employee getEmpById (Integer id) {System.err.println ("start query" + id + "employee"); Employee employee = employeeMapper.getEmpById (id); return employee } / * * @ CachePut: both call the method (which must be executed) and update the cached data * @ param employee * @ return * / @ CachePut (value = "emp", key = "# result.id") public Employee updateEmp (Employee employee) {System.err.println ("start updating" + employee.getId () + "employee"); employeeMapper.updateEmp (employee); return employee } / * * @ CacheEvict: cache clearing * @ param id * / @ CacheEvict (value = "emp", beforeInvocation = true) public void deleteEmp (Integer id) {System.err.println ("delete" + id + "employee"); int I = 10 id 0;}
10. Write the Controller class
Package com.henya.springboot.controller;import com.henya.springboot.bean.Employee;import com.henya.springboot.service.EmployeeService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RestController;/** * @ Description: * @ Author:HenYa * @ CreatTime:2019/12/1 12:44 * / @ RestControllerpublic class EmployeeController {@ Autowired EmployeeService employeeService @ GetMapping ("/ emp/ {id}") public Employee getEmpById (@ PathVariable ("id") Integer id) {Employee employee = employeeService.getEmpById (id); return employee;} @ GetMapping ("/ emp") public Employee updateEmp (Employee employee) {Employee emp = employeeService.updateEmp (employee); return emp;}} II. Test whether SpringBoot integrates Redis successfully.
1. In the browser access, you can also use the test class. The author uses the browser to access http://localhost:8080/emp/1 for testing. The console will prompt you to start querying employee No. 1 on the first visit, as shown in the figure.
2. When you visit again, there is no sql log on the console, as shown in the figure.
3. There is data when using RedisDesktopManager tool to view redis, and cacheName is emp, as shown in the figure.
It's just that the emp object is serialized. Looking at the source code, we can see that Redis uses Jdk for serialization by default.
Static RedisSerializer java (@ Nullable ClassLoader classLoader) {return new JdkSerializationRedisSerializer (classLoader);}
There are several implementations of the RedisSerializer interface:
What we often use is serialization in json format. But you need to customize the RedisCacheManager.
III. Custom RedisCacheManagerpackage com.henya.springboot.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheConfiguration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.cache.RedisCacheWriter;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import org.springframework.data.redis.serializer.RedisSerializer / * * @ Description: * @ Author:HenYa * @ CreatTime:2019/12/6 20:50 * / @ Configurationpublic class MyRedisConfig {@ Bean public RedisCacheManager empCacheManager (RedisConnectionFactory redisConnectionFactory) {/ / RedisCacheManager redisCacheManager = new RedisCacheManager (redisConnectionFactory); RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter (redisConnectionFactory); RedisSerializer redisSerializer = new GenericJackson2JsonRedisSerializer (); RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair.fromSerializer (redisSerializer); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig (). SerializeValuesWith (pair); / / CacheName will be used as key prefix return new RedisCacheManager (redisCacheWriter, redisCacheConfiguration) by default }} above is all the content of the article "how to build SpringBoot2.X in Redis Framework". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
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.