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

SpringBoot Integration Redis how to use RedisRepositories

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Most people do not understand the knowledge points of this article "SpringBoot Integration Redis how to use RedisRepositories", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "SpringBoot Integration Redis how to use RedisRepositories" article.

SpringBoot integrates Redis1. Add redis dependency org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool22. Add redis configuration information to application.properties spring.redis.host=127.0.0.1# Redis server connection port spring.redis.port=6379# Redis server connection password (default is empty) spring.redis.password=# connection pool maximum number of connections (use negative values for no limit) spring.redis.lettuce.pool.max-active=8# connection pool maximum blocking wait time (use negative values for no limit) spring.redis.lettuce .pool.max-maximum idle connections in wait=-1# connection pool minimum idle connection spring.redis.lettuce.pool.min-idle=0# connection timeout in milliseconds) add annotation configuration @ EnableCaching@EnableRedisRepositories// annotation in spring.redis.timeout=300003.SpringBoot startup class use RedisRepositories//CRUD operation will manipulate data @ SpringBootApplicationpublic class RedisApplication {public in redis Static void main (String [] args) {SpringApplication.run (RedisApplication.class) Args) }} 4. Creating the entity class Entity@Data@RedisHash ("user") / / RedisHash is very important / / user means that all UserEntity saving operations after creating a new user collection in redis / / will be saved in the user collection / / when saving the Key format is-- user:idpublic class UserEntity {@ Id private Long id; private String name; private Integer age; private Date createTime = new Date ();} 5. Create Dao layer-data manipulation layer @ Repositorypublic interface UserDao extends CrudRepository {} 6. Create a Service layer-the service layer @ Servicepublic class UserService {@ Autowired private UserDao userDao; / / because RedisRepositories is used, a simple crud will not have to use RedisTemplate// @ Autowired// private RedisTemplate redisTemplate; / * to deposit redis * @ param user * / public void save (UserEntity user) {/ / redisTemplate.opsForValue (). Set (new Random (). NextDouble () + ", user) UserDao.save (user);} / * find the corresponding value * @ param id * @ return * / public UserEntity findOne (Long id) {/ / UserEntity user = (UserEntity) redisTemplate.opsForValue (). Get (key); UserEntity user = userDao.findById (id). Get (); return user;}} 7. Create Controller layer-Control layer @ RestController@RequestMapping ("user") public class UserController {@ Autowired private UserService userService; / * Save to redis * @ return * / @ GetMapping ("save") public String save () {UserEntity user = new UserEntity (); user.setName (String.valueOf (new Random (). NextInt (100000)); user.setAge (new Random (). NextInt (100000)) UserService.save (user); System.out.println (user.toString ()); return "success";} / * find value * @ param id * @ return * / @ GetMapping ("find/ {id}") public String find (@ PathVariable Long id) {UserEntity user = userService.findOne (id); System.out.println (user) from redis according to key Return "success";}} 8.redis configuration class @ Configurationpublic class RedisConfig {@ Bean public RedisTemplate redisTemplate (RedisConnectionFactory factory) {RedisTemplate template = new RedisTemplate (); template.setConnectionFactory (factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class); ObjectMapper om = new ObjectMapper (); om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL) Jackson2JsonRedisSerializer.setObjectMapper (om); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer (); / / key uses the serialization method of String template.setKeySerializer (stringRedisSerializer); / / key of hash also uses the serialization method of String template.setHashKeySerializer (stringRedisSerializer); / / value serialization uses jackson template.setValueSerializer (jackson2JsonRedisSerializer); / / value serialization of hash adopts jackson template.setHashValueSerializer (jackson2JsonRedisSerializer) The structure in template.afterPropertiesSet (); return template;}} Redis is

Redis Encapsulation tool Class @ Componentpublic class RedisUtils {@ Autowired private RedisTemplate redisTemplate / / = = common== / * specify cache expiration time * * @ param key key * @ param time time (seconds) * @ return * / public boolean expire (String key Long time) {try {if (time > 0) {redisTemplate.expire (key, time, TimeUnit.SECONDS) } return true;} catch (Exception e) {e.printStackTrace (); return false }} / * get expiration time based on key * * @ param key key cannot return 0 for null * @ return time (seconds) represents permanent validity * / public long getExpire (String key) {return redisTemplate.getExpire (key, TimeUnit.SECONDS) } / * determine whether key exists * * @ param key key * @ return true does not exist false does not exist * / public boolean hasKey (String key) {try {return redisTemplate.hasKey (key) } catch (Exception e) {e.printStackTrace (); return false }} / * * delete cache * * @ param key can pass a value or multiple * / @ SuppressWarnings ("unchecked") public void del (String...) Key) {if (key! = null & & key.length > 0) {if (key.length = = 1) {redisTemplate.delete (key [0]);} else {redisTemplate.delete (CollectionUtils.arrayToList (key)) } / / = = String== / * ordinary cache acquires * * @ param key key * @ return value * / public Object get (String key) {return key = = null? Null: redisTemplate.opsForValue () .get (key) } / * ordinary cache put in * * @ param key key * @ param value value * @ return true false failed * / public boolean set (String key, Object value) {try {redisTemplate.opsForValue () .set (key, value) Return true;} catch (Exception e) {e.printStackTrace (); return false }} / * ordinary cache put and set time * * @ param key key * @ param value value * @ param time time (seconds) time is greater than 0 if time is less than or equal to 0, it will be set indefinitely * @ return true success false failed * / public boolean set (String key Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue () .set (key, value, time, TimeUnit.SECONDS) } else {set (key, value);} return true;} catch (Exception e) {e.printStackTrace (); return false }} / * incremental * * @ param key key * @ param delta to add several times (greater than 0) * @ return * / public long incr (String key, long delta) {if (delta)

< 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= /** * HashGet * * @param key 键 不能为null * @param item 项 不能为null * @return 值 */ public Object hget(String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * 获取hashKey对应的所有键值 * * @param key 键 * @return 对应的多个键值 */ public Map hmget(String key) { return redisTemplate.opsForHash().entries(key); } /** * HashSet * * @param key 键 * @param map 对应多个键值 * @return true 成功 false 失败 */ public boolean hmset(String key, Map map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return true成功 false失败 */ public boolean hmset(String key, Map map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time >

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