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 to analyze the process of SpringBoot integrating SpringCache and Redis

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to analyze the process of SpringBoot integration of SpringCache and Redis. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

1. Install redis

a. Since there is no official Windows version, we need to download redis developed by Microsoft at:

Https://github.com/MicrosoftArchive/redis/releases

b. After decompressing, open the cmd interface in the redis root directory, type: redis-server.exe redis.windows.conf, start redis (close the cmd window and stop)

two。 Use

a. Create a SpringBoot project and select maven dependency

Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-data-redis.

b. Configure application.yml Profil

Server: port: 8080spring: # redis related configuration redis: database: 0 host: localhost port: 6379 password: jedis: pool: # maximum number of connections in connection pool (using negative values for unlimited) max-active: 8 # maximum blocking wait time in connection pool (using negative values for unlimited) max-wait:-1ms # maximum idle connections in connection pool max-idle: minimum idle connections in 5 # connection pool Then min-idle: 0 # connection timeout (milliseconds) defaults to 2000ms timeout: 2000ms # thymeleaf Hot Update thymeleaf: cache: false

c. Create a RedisConfig configuration class

@ Configuration@EnableCaching / / enable cache public class RedisConfig {/ * cache manager * @ param redisConnectionFactory * @ return * / @ Bean public RedisCacheManager cacheManager (RedisConnectionFactory redisConnectionFactory) {/ / generate a default configuration that can be customized through the config object RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig () / / set the default expiration time of the cache, also using Duration to set config = config.entryTtl (Duration.ofMinutes (30)) / / set key to string serialization .serializeKeysWith (RedisSerializationContext.SerializationPair.fromSerializer (new StringRedisSerializer () / set value to json serialization .serializeValuesWith (RedisSerializationContext.SerializationPair.fromSerializer (jackson2JsonRedisSerializer () / / do not cache null values .serileCachingNullValues (); / / apply a different configuration Map configMap = new HashMap () to each cache space ConfigMap.put ("userCache", config.entryTtl (Duration.ofSeconds (60); / / initialize a cacheManager RedisCacheManager cacheManager = RedisCacheManager.builder (redisConnectionFactory) / / default configuration .cacheDefaults (config) / / Special configuration (be sure to call this method to set the initialization cache name before initializing the relevant configuration) .initialCacheNames (configMap.keySet ()) .withInitialCacheConfigurations (configMap) .build (); return cacheManager } / * Redis template class redisTemplate * @ param factory * @ return * / @ Bean public RedisTemplate redisTemplate (RedisConnectionFactory factory) {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (factory); / / key uses String serialization template.setKeySerializer (new StringRedisSerializer ()); / / hash key also uses String serialization template.setHashKeySerializer (new StringRedisSerializer ()); / / value serialization uses jackson template.setValueSerializer (jackson2JsonRedisSerializer ()) / / value serialization of hash adopts jackson template.setHashValueSerializer (jackson2JsonRedisSerializer ()); return template;} / * json serialization * @ return * / private RedisSerializer jackson2JsonRedisSerializer () {/ / use Jackson2JsonRedisSerializer to serialize and deserialize the value of redis Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer (Object.class); / / json to object class, if not set default, json will be converted to hashmap ObjectMapper mapper = new ObjectMapper (); mapper.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY) Mapper.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper (mapper); return serializer;}}

d. Create an entity entity class

Public class User implements Serializable {private int id; private String userName; private String userPwd; public User () {} public User (int id, String userName, String userPwd) {this.id = id; this.userName = userName; this.userPwd = userPwd;} public int getId () {return id;} public void setId (int id) {this.id = id;} public String getUserName () {return userName;} public void setUserName (String userName) {this.userName = userName;} public String getUserPwd () {return userPwd } public void setUserPwd (String userPwd) {this.userPwd = userPwd;}}

e. Create Service

@ Servicepublic class UserService {/ / query: first check whether there is a cache. If so, directly fetch the data in the cache. If not, run the code in the method and cache @ Cacheable (value = "userCache", key = "user:' + # userId") public User getUser (int userId) {System.out.println ("execute this method means there is no cache"); return new User (userId, "username (get) _" + userId, "password _" + userId) } / / add: run the code in the method and cache @ CachePut (value = "userCache", key = "'user:' + # user.id") public User addUser (User user) {int userId = user.getId (); System.out.println ("add cache"); return new User (userId, "username (add) _" + userId, "password _" + userId) } / / delete: delete cache @ CacheEvict (value = "userCache", key = "'user:' + # userId") public boolean deleteUser (int userId) {System.out.println ("delete cache"); return true;} @ Cacheable (value = "common", key = "' common:user:' + # userId") public User getCommonUser (int userId) {System.out.println ("execute this method to indicate that there is no cache (test whether the public configuration is effective)") Return new User (userId, user name (common) _ "+ userId," password _ "+ userId);}}

f. Create Controller

RestController@RequestMapping ("/ user") public class UserController {@ Resource private UserService userService; @ RequestMapping ("/ getUser") public User getUser (int userId) {return userService.getUser (userId);} @ RequestMapping ("/ addUser") public User addUser (User user) {return userService.addUser (user);} @ RequestMapping ("/ deleteUser") public boolean deleteUser (int userId) {return userService.deleteUser (userId);} @ RequestMapping ("/ getCommonUser") public User getCommonUser (int userId) {return userService.getCommonUser (userId);}}

@ Controllerpublic class HomeController {/ / default page @ RequestMapping ("/") public String login () {return "test";}}

g. Under the templates directory, write the book test.html page

Test .row {margin:10px 0px;} .col {display: inline-block; margin:0px 5px;}

Test user ID:

Get users

Add user

Delete user

Get user (common)

(function () {$("# getuser-btn"). On ("click", function () {var userId = $("# userid-input"). Val (); $.ajax ({url: "/ user/getUser", data: {userId: userId}, dataType: "json", success: function (data) {$("# result-p"). Text ("id [" + data.id + ", userName [" + data.userName + "], userPwd [" + data.userPwd + "]) }, error: function (e) {$("# result-p") .text ("system error!") ;},})); $("# adduser-btn") .on ("click", function () {var userId = $("# userid-input") .val () $.ajax ({url: "/ user/addUser", data: {id: userId}, dataType: "json", success: function (data) {$("# result-p"). Text ("id [" + data.id + ", userName [" + data.userName + "], userPwd [" + data.userPwd + "]");}, error: function (e) {$("# result-p"). Text ("system error!") ;},})); $("# deleteuser-btn"). On ("click", function () {var userId = $("# userid-input"). Val (); $.ajax ({url: "/ user/deleteUser", data: {userId: userId}, dataType: "json", success: function (data) {$("# result-p") .text (data);}, error: function (e) {$("# result-p"). Text ("system error!") ;},})); $("# getcommonuser-btn") .on ("click", function () {var userId = $("# userid-input") .val () $.ajax ({url: "/ user/getCommonUser", data: {userId: userId}, dataType: "json", success: function (data) {$("# result-p"). Text ("id [" + data.id + ", userName [" + data.userName + "], userPwd [" + data.userPwd + "]");}, error: function (e) {$("# result-p"). Text ("system error!") ;},})})

On how to analyze SpringBoot integration of SpringCache and Redis process to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Development

Wechat

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

12
Report