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 integrate redis in springboot to realize distributed Lock

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

This article is about how to integrate redis in springboot to achieve distributed locks. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

Summary: it is relatively simple for springboot to integrate redis. Import the package (import redis pom file), write the basic configuration of redis in the configuration file, customize a redisTemplate (template), and write a tool class by yourself.

The important thing to note is that you need to import a fastJson pom file yourself, in order to facilitate the serialization of objects.

First: import pom file

Org.springframework.boot

Spring-boot-starter-data-redis

Com.alibaba

Fastjson

1.2.56

Step 2: configure the properties in redis in the configuration file

Redis:

Database: 0

Host: localhost

Port: 6379

Password:

Pool:

Max-active: 200

Max-wait:-1 # maximum blocking time of connection pool. A negative value indicates no limit.

Max-idle: 10

Min-idle: 0 # minimum idle

Timeout: 1000

Step 3: customize the template class

/ * *

* customize a redis template and implement serialization

* @ param factory

* @ return

, /

@ Bean

The @ SuppressWarnings ("all") / / function tells the editor not to display a warning message after the compilation is complete

Public RedisTemplate redisTemplate (RedisConnectionFactory factory) {

/ / introduce the original redisTemplate to implement injection

RedisTemplate template = new RedisTemplate ()

/ / inject the factory into the stringTemplate

Template.setConnectionFactory (factory)

/ / jackSon serialization object is adopted

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)

/ / serialize a pair of String

StringRedisSerializer stringRedisTemplate = new StringRedisSerializer ()

Template.setKeySerializer (stringRedisTemplate)

Template.setHashKeySerializer (stringRedisTemplate)

Template.setValueSerializer (jackson2JsonRedisSerializer)

Template.setHashKeySerializer (jackson2JsonRedisSerializer)

Template.afterPropertiesSet ()

Return template

}

Step 4: write a tool class yourself

@ Component

Public class RedisUtil {

@ Autowired

Private RedisTemplate redisTemplate

/ * *

* specify the expiration time for the specified key

* @ param key

* @ param time

* @ 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 the specified key failure time

* @ param key

* @ return

, /

Public long getExpire (String key) {

Return redisTemplate.getExpire (key, TimeUnit.SECONDS)

}

/ * *

* determine whether key exists

* @ param key

* @ return

, /

Public boolean hasKey (String key) {

Return redisTemplate.hasKey (key)

}

/ * *

* Delete multiple key

* @ param key

, /

Public void delete (String... Key) {

/ / A pair of key values are judged

If (key! = null & & key.length > 0) {

If (key.length = = 1) {

RedisTemplate.delete (key [0])

} else {

RedisTemplate.delete ((Collection) CollectionUtils.arrayToList (key))

}

}

}

/ * *

* get the value size corresponding to the key value

* @ param key

* @ return

, /

Public Object get (String key) {

Return key==null? Null: redisTemplate.opsForValue () .get (key)

}

/ * *

* store key and value values

* @ param key

* @ param value

* @ return

, /

Public void set (String key, Object value) {

RedisTemplate.opsForValue () .set (key value)

}

/ * *

* store a valid value for key

* @ param key

* @ param value

* @ param time

, /

Public void set (String key, Object value, long time) {

If (time > 0) {

RedisTemplate.opsForValue () .set (key, value, time, TimeUnit.SECONDS)

} else {

RedisTemplate.opsForValue () .set (key value)

}

}

/ * *

* increasing dalta factor for key

* @ param key

* @ param dalta

* @ return

, /

Public long incr (String key, long dalta) {

If (dalta

< 0){ throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, dalta); } /** * 对key进行递减多少个元素 * @param key * @param delta * @return */ public long decr(String key, long delta){ if (delta < 0){ throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().decrement(key, delta); } /** * hash取值 * @param key * @param item * @return */ public Object hget(String key, String item){ return redisTemplate.opsForHash().get(key, item); } /** * 获取key下面的所有值 * @param key * @return */ public Map hmget(String key){ return redisTemplate.opsForHash().entries(key); } /** * 将对象存储进hash中去 * @param key * @param map */ public void hmset(String key, Map map){ redisTemplate.opsForHash().putAll(key, map); } /** * 对其中的key进行设置时效时间 * @param key * @param map * @param time */ public void hmset(String key, Map map, long time){ redisTemplate.opsForHash().putAll(key, map); if (time >

0) {

Expire (key, time)

}

}

/ * *

* inject a transfer of data into a table

* @ param key

* @ param item

* @ param value

, /

Public void hset (String key, String item, Object value) {

RedisTemplate.opsForHash () .put (key, item, value)

}

/ * *

* set an expiration time for key

* @ param key

* @ param item

* @ param value

* @ param time

, /

Public void hset (String key, String item, Object value, long time) {

RedisTemplate.opsForHash () .put (key item,value)

If (time > 0) {

Expire (key, time)

}

}

/ * *

* Delete the value in hash

* @ param key

* @ param item

, /

Public void hdel (String key, Object... Item) {

RedisTemplate.opsForHash () .delete (key item)

}

/ * *

* determine whether it exists in the hash table

* @ param key

* @ param item

, /

Public void hHashKey (String key, String item) {

RedisTemplate.opsForHash () .hasKey (key item)

}

/ * *

* give a value to what exists, and if it exists, it will be created and added to it.

* @ param key

* @ param item

* @ param by

, /

Public void hincr (String key, String item, double by) {

RedisTemplate.opsForHash () .increment (key, item, by)

}

/ * *

* reduce the existing key by one value

* @ param key

* @ param item

* @ param by

, /

Public void hdecr (String key, String item, double by) {

RedisTemplate.opsForHash () increment (key, item,-by)

}

/ * *

* get a value from set

* @ param key

* @ return

, /

Public Set sGet (String key) {

Return redisTemplate.opsForSet () members (key)

}

/ / List

/ * *

* take a value from list

* @ param key

* @ param start

* @ param end

* @ return

, /

Public List lGet (String key, long start, long end) {

Return redisTemplate.opsForList () .range (key, start, end)

}

/ * *

* get the length of the list

* @ param key

* @ return

, /

Public long lGetLilstSize (String key) {

Return redisTemplate.opsForList () size (key)

}

/ * *

* get the value in list through the index

* @ param key key

* @ param index > = 0, heading 0, the second element of 1, and so on; index 0) {

Expire (key, time)

}

}

/ * *

* save an entire List collection to the cache

* @ param key

* @ param value

, /

Public void lSet (String key, List value) {

RedisTemplate.opsForList () .rightPushAll (key value)

}

/ * *

* set an expiration time for the key value

* @ param key

* @ param value

* @ param time

, /

Public void lSet (String key, List value, long time) {

RedisTemplate.opsForList () .rightPushAll (key value)

If (time > 0) {

Expire (key, time)

}

}

/ * *

* store a value value in the corresponding index

* @ param key

* @ param index

* @ param value

, /

Public void lUpdateIndex (String key, long index, Object value) {

RedisTemplate.opsForList () .set (key, index, value)

}

/ * *

* delete the value of the corresponding index location

* @ param key

* @ param count

* @ param value

* @ return

, /

Public void lRemove (String key, long count, Object value) {

RedisTemplate.opsForList () .remove (key, count, value)

}

}

The process of realizing distributed lock by Redssion mainly consists of five steps.

Import the pom file, write an interface to acquire distributed locks, define a management interface for distributed locks, define a class to implement the management of distributed interfaces just defined, and define an exception that does not acquire distributed locks.

This part of the code is implemented by the above springboot integration redis foundation, and the imported pom file:

Org.redisson

Redisson

3.7.0

Step 2: define after acquiring the lock

Public interface AquiredLockWorker {

/ * *

* methods for handling specific business logic after acquiring locks

* @ return

* @ throws Exception

, /

T invokeAfterLockAquire () throws Exception

Step 3: distributed management interface

Public interface DistributedLocker {

/ * *

* parameters to be entered when acquiring the lock

* @ param resourceName

* @ param worker

* @ param

* @ return

* @ throws Exception

, /

T lock (String resourceName, AquiredLockWorker worker) throws Exception

/ * *

* the parameters need to be entered when acquiring the lock, and the validity period of the lock is set.

* @ param

* @ param resourceName

* @ param worker

* @ param time

* @ throws Exception

, /

T lock (String resourceName, AquiredLockWorker worker, long time) throws Exception

Step 4: define a class-a class that implements a distributed interface

@ Component

Public class RedisLock implements DistributedLocker {

Private final static String name = "redisLock"

@ Autowired

Private RedissonConnector redissonConnector

@ Override

Public T lock (String resourceName, AquiredLockWorker worker) throws Exception {

Return lock (resourceName, worker, 100)

}

@ Override

Public T lock (String resourceName, AquiredLockWorker worker, long time) throws Exception {

RedissonClient redissonClient = redissonConnector.getRedissonClient ()

RLock lock = redissonClient.getLock (name + resourceName)

/ / wait 100 seconds to release the lock

Boolean flag = lock.tryLock (100,100, time, TimeUnit.SECONDS)

If (flag) {

/ / the code must be designed this way

Try {

/ / the method of getting the business executed after the lock is acquired

Return worker.invokeAfterLockAquire ()

} finally {

Lock.unlock ()

}

}

/ / when the lock is not obtained, it will be reported that there is no exception to take the lock

Throw new UnsupportedOperationException ()

}

Step 5: define exception classes

Public class UnableToAquireLockException extends RuntimeException {

/ * *

* define a no-parameter construction

, /

Public UnableToAquireLockException () {}

/ * *

* print out the wrong message

* @ param message

, /

Public UnableToAquireLockException (String message) {

Super (message)

}

/ * *

* print error messages and exception types

* @ param message

* @ param cause

, /

Public UnableToAquireLockException (String message, Throwable cause) {

Super (message, cause)

}

Call:

@ RestController

Public class RedisController {

@ Autowired

Private DistributedLocker distributedLocker

@ RequestMapping (value = "index")

Public String index () throws Exception {

DistributedLocker.lock ("test", new AquiredLockWorker () {

@ Override

Public Object invokeAfterLockAquire () throws Exception {

System.out.println ("logical processing is done directly here")

Thread.sleep (100)

Return null

}

});

Return "hello redis"

}

The above is how to integrate redis in springboot to achieve distributed locks. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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.

Share To

Servers

Wechat

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

12
Report