Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does SpringBoot integrate redis's cache?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article gives you a detailed introduction to SpringBoot's integration of redis caching. Most of the knowledge points are often used by everyone, so I will share them for you as a reference. Let's follow the editor and have a look.

Enable remote access:

Find the redis.conf file in redis and edit it (found in the installation path)

Vim. / redis.conf

1. Find bind 127.0.0.1 and comment it out

By default, 127.0.0.1 can only be accessed locally and can be accessed by ip after being commented out.

2. Change the value of protected-mode attribute to no

Can be accessed by IP after commenting out and disabling protected mode

3. Modify the daemonize attribute and change no to yes.

Setting daemonize to yes starts running in the background

4. Open port 6379

/ sbin/iptables-I INPUT-p tcp-- dport 6379-j ACCEPT

It is not open to the public by default. 6379

5. Start redis

Redis-server / myconf/redis.conf

By default, redis-server is under the / usr/local/bin path, and redis.conf is under the redis installation path.

6. Test the connection

Redis-cli-h 192.168.126.129-p 6379

Redis-cli-h redis server IP-p 6379-a password (do not write blank without setting redis password, otherwise an error will be reported)

Java code writing:

Project source code structure

A user table

Code:

Pom.xml file (can be added or modified according to your own needs)

Org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 1.3.2 mysql mysql-connector-java 5.1.39 org.springframework.boot Spring-boot-starter-test test org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-cache

The following is springboot's configuration file application.yml, configuration redis (all with annotations and explanations)

Server: port: 8081 # Database connection spring: datasource: url: jdbc:mysql://localhost:3306/mytest_springboot_cache?useUnicode=true driver-class-name: com.mysql.jdbc.Driver username: root password: lzh # # Redis configuration redis: # # Redis database index (default is 0) database: 0 # # Redis server address host: 192.168.126.129 # # Redis server connection Connect port port: 6379 # # Redis server connection password (default is empty) password: jedis: pool: # # maximum number of connections in connection pool (use negative values to indicate no limit) # spring.redis.pool.max-active=8 max-active: 8 # # maximum blocking wait time in connection pool (use negative values to indicate no limit) # spring.redis.pool.max-wait=-1 max-wait:-1 # # maximum idle connection in connection pool # spring.redis.pool.max-idle=8 max-idle: 8 # # minimum idle connection in connection pool # spring.redis.pool.min-idle=0 min-idle: 0 # # connection timeout (millisecond) Timeout: 1200 # disable the default cache for themilef Hot load effective thymeleaf: cache: false # mybatis underline hump configuration configuration: map-underscore-to-camel-case: true # another way to print statements log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # statements when printing sql logging: level: com: acong: dao: debug file: d:/logs/bsbdj.log

Then there is the entity class, which is relatively simple to say.

Package com.lzh.springbootstudytest.bean; import java.io.Serializable; / * * @ author lzh * create 2019-09-18-22:32 * / public class User implements Serializable {private static final long serialVersionUID = 1L; private int uid; private String userName; private String passWord; private int salary; public int getUid () {return uid;} public void setUid (int uid) {this.uid = uid } 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;} public int getSalary () {return salary;} public void setSalary (int salary) {this.salary = salary } public User (int uid, String userName, String passWord, int salary) {super (); this.uid = uid; this.userName = userName; this.passWord = passWord; this.salary = salary;} public User () {super ();}

This is the controller class that exposes interface access

Package com.lzh.springbootstudytest.controller; import com.lzh.springbootstudytest.bean.User;import com.lzh.springbootstudytest.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController; import java.util.HashMap;import java.util.List;import java.util.Map / * @ author lzh * create 2019-09-18-22:36 * / @ RestControllerpublic class TestController {@ Autowired private UserService userService; @ RequestMapping ("/ queryAll") public List queryAll () {List lists = userService.queryAll (); return lists;} @ RequestMapping ("/ findUserById") public Map findUserById (@ RequestParam int id) {User user = userService.findUserById (id); Map result = new HashMap () Result.put ("uid", user.getUid ()); result.put ("uname", user.getUserName ()); result.put ("pass", user.getPassWord ()); result.put ("salary", user.getSalary ()); return result;} @ RequestMapping ("/ updateUser") public String updateUser () {User user = new User (); user.setUid (1) User.setUserName ("cat"); user.setPassWord ("miaomiao"); user.setSalary (4000); int result = userService.updateUser (user); if (result! = 0) {return "update user success";} return "fail";} @ RequestMapping ("/ deleteUserById") public String deleteUserById (@ RequestParam int id) {int result = userService.deleteUserById (id) If (result! = 0) {return "delete success";} return "delete fail";}}

Configure redistemplate serialization

Package com.lzh.springbootstudytest.config; 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.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.core.*;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration / * * @ author lzh * create 2019-09-24-15:07 * / @ Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport {/ * Select redis as the default caching tool * @ param redisConnectionFactory * @ return * / / * @ Bean / / springboot 1.xx public CacheManager cacheManager (RedisTemplate redisTemplate) {RedisCacheManager rcm = new RedisCacheManager (redisTemplate); return rcm } * / @ Bean public CacheManager cacheManager (RedisConnectionFactory redisConnectionFactory) {RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig () .en tryTtl (Duration.ofHours (1)); / / set cache validity period for one hour return RedisCacheManager .builder (RedisCacheWriter.nonLockingRedisCacheWriter (redisConnectionFactory)) .cacheDefaults (redisCacheConfiguration) .build () } / * * retemplate related configuration * @ param factory * @ return * / @ Bean public RedisTemplate redisTemplate (RedisConnectionFactory factory) {RedisTemplate template = new RedisTemplate (); / / configure connection factory template.setConnectionFactory (factory) / / use Jackson2JsonRedisSerializer to serialize and deserialize the value of redis (using JDK serialization by default) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); / / specify the domain, field,get and set to be serialized, as well as the modifier range. ANY includes private and public om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY) / / specify the type of serialized input. Classes must be non-final-decorated, final-decorated classes, such as String,Integer, which will run exception om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper (om); / / json serialized template.setValueSerializer (jacksonSeial) / / use StringRedisSerializer to serialize and deserialize the key value of redis template.setKeySerializer (new StringRedisSerializer ()); / / set hash key and value serialization mode template.setHashKeySerializer (new StringRedisSerializer ()); template.setHashValueSerializer (jacksonSeial); template.afterPropertiesSet (); return template } / * * data manipulation on hash type * * @ param redisTemplate * @ return * / @ Bean public HashOperations hashOperations (RedisTemplate redisTemplate) {return redisTemplate.opsForHash () } / * * operate on redis string type data * * @ param redisTemplate * @ return * / @ Bean public ValueOperations valueOperations (RedisTemplate redisTemplate) {return redisTemplate.opsForValue () } / * * data operations on linked list types * * @ param redisTemplate * @ return * / @ Bean public ListOperations listOperations (RedisTemplate redisTemplate) {return redisTemplate.opsForList () } / * * data operations on unordered collection types * * @ param redisTemplate * @ return * / @ Bean public SetOperations setOperations (RedisTemplate redisTemplate) {return redisTemplate.opsForSet () } / * * data operations on ordered collection types * * @ param redisTemplate * @ return * / @ Bean public ZSetOperations zSetOperations (RedisTemplate redisTemplate) {return redisTemplate.opsForZSet ();}}

Then there is the Mapper persistence layer Dao, where it is convenient to write with annotations, or you can use mybatis's xml configuration file to write sql statements.

Package com.lzh.springbootstudytest.mapper; import com.lzh.springbootstudytest.bean.User;import org.apache.ibatis.annotations.*; import java.util.List; / * * @ author lzh * create 2019-09-18-22:32 * / @ Mapperpublic interface UserDao {@ Select ("select * from user") List queryAll (); @ Select ("select * from user where uid = # {id}") User findUserById (int id) @ Update ("UPDATE USER SET username = CASE WHEN (# {userName}! = NULL) AND (# {userName}! =') THEN # {userName}, PASSWORD = CASE WHEN (# {passWord}! = NULL) AND (# {passWord}! ='') THEN # {passWord}, salary = CASE WHEN (# {salary}! = 0) THEN # {salary} WHERE uid = # {uid}") int updateUser (@ Param ("user") User user) @ Delete ("delete from user where uid = # {id}") int deleteUserById (int id);}

Service layer, here is mainly to use redis template to write

Package com.lzh.springbootstudytest.service; import com.lzh.springbootstudytest.bean.User;import com.lzh.springbootstudytest.mapper.UserDao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Service; import java.util.List;import java.util.concurrent.TimeUnit / * author lzh * create 2019-09-18-22:33 * / @ Servicepublic class UserService {@ Autowired private UserDao userDao; @ Autowired private RedisTemplate redisTemplate; public List queryAll () {return userDao.queryAll () } / * get the user policy: get the user from the cache first, then fetch the data from the data table if not, and then write the data to the cache * / public User findUserById (int id) {String key = "user_" + id; ValueOperations operations = redisTemplate.opsForValue (); / / determine whether there is a cache boolean hasKey = redisTemplate.hasKey (key) with the key key in redis If (hasKey) {User user = operations.get (key); System.out.println ("get data from cache:" + user.getUserName ()); System.out.println ("- -"); return user } else {User user = userDao.findUserById (id); System.out.println ("query database to get data:" + user.getUserName ()); System.out.println ("- -") / / write cache operations.set (key, user, 5, TimeUnit.HOURS); return user;}} / * update user policy: update the data table first, delete the original cache after success, and then update the cache * / public int updateUser (User user) {ValueOperations operations = redisTemplate.opsForValue () Int result = userDao.updateUser (user); if (result! = 0) {String key = "user_" + user.getUid (); boolean haskey = redisTemplate.hasKey (key); if (haskey) {redisTemplate.delete (key); System.out.println ("remove key- >" + key) } / / add the updated data to the cache User userNew = userDao.findUserById (user.getUid ()); if (userNew! = null) {operations.set (key, userNew, 3, TimeUnit.HOURS);}} return result Delete user policy: delete the data in the data table, and then delete the cache * / public int deleteUserById (int id) {int result = userDao.deleteUserById (id); String key = "user_" + id; if (result! = 0) {boolean hasKey = redisTemplate.hasKey (key) If (hasKey) {redisTemplate.delete (key); System.out.println ("key removed from cache:" + key);}} return result;}}

Here, RedisTemplate is mainly used for remote redis operations. Each time you access the interface exposed by controller, you first determine whether the data exists in the redis cache. If it does not exist, read the data from the database, then save it to the redis cache, and take it out of the cache directly the next time you access it.

In this way, you don't have to execute sql statements every time, and you can improve access speed. However, when saving data to the cache, by setting keys and values and timeout deletion, be careful not to set the timeout deletion cache for too long, otherwise it will put pressure on the server.

Execute the startup class of spring boot and access http://localhost:8081/findUserById?id=1

To access http://localhost:8081/findUserById?id=1 again is to get the saved data from the cache.

The above is the detailed introduction of SpringBoot integration redis cache, the content is more comprehensive, the editor believes that there may be some knowledge points that we may see or use in our daily work. I hope you can learn more from this article.

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.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report