spring cloud alibaba整合redis,并实现redisson分布式锁

1. 引入相关jar包,核心jar包有两个,配置如下

        <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--redisSon-->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>${redisson.version}</version>
        </dependency>

2. bootstrap.yml中添加配置

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 密码
    # 指定数据库 默认是0
    database: 0
    timeout: 1000

3.添加redis配置类

package com.body.park.user.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author xxx
 * @DATE 2022/3/27 9:33
 * redis配置类
 */
@Configuration
public class RedisConfiguration {

    /**
     * 注入redisTemplate
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

4. 使用redis

package com.body.park.user.business;

import cn.hutool.json.JSONUtil;
import com.body.park.order.client.OrderTestService;
import com.body.park.user.client.UserTestService;
import com.body.park.user.entity.TUser;
import com.body.park.user.service.ITUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Author xxx
 * @DATE 2022/3/13 20:32
 */
@DubboService
@Component
@Slf4j
public class UserTestServiceImpl implements UserTestService {

    @Autowired
    private RedisTemplate redisTemplate;

    //获取redis的值
    public String findRedisKey(String key) {
        Object result = redisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(result)) {
            return "fail";
        }
        return result.toString();
    }

    //设置redis的值
    public String setRedisKey(String key) {
        String value = key + "value";
        redisTemplate.opsForValue().set(key, value, 100, TimeUnit.SECONDS);
        return value;
    }
}

5. 使用redis实现分布式锁

需要引入的jar是:

        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>${redisson.version}</version>
        </dependency>

6. 添加配置类 RedisSonConfiguration.java

package com.body.park.user.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author xxx
 * @DATE 2022/3/27 11:13
 */
@Configuration
public class RedisSonConfiguration {

    @Value("${spring.redis.host}")
    private String address;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private String database;

    @Value("${spring.redis.timeout}")
    private String timeout;

    @Bean
    public RedissonClient redisson() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress(address())
                .setPassword(password)
                .setDatabase(Integer.parseInt(database))
                .setConnectTimeout(Integer.parseInt(timeout));
        return Redisson.create(config);
    }

    /**
     * 生成address
     * @return
     */
    private String address() {
        return "redis://" + address + ":" + port;
    }
}

7.redisson的使用

package com.body.park.user.business;

import cn.hutool.json.JSONUtil;
import com.body.park.order.client.OrderTestService;
import com.body.park.user.client.UserTestService;
import com.body.park.user.entity.TUser;
import com.body.park.user.service.ITUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @Author chaoxian.wu
 * @DATE 2022/3/13 20:32
 */
@DubboService
@Component
@Slf4j
public class UserTestServiceImpl implements UserTestService {
    //定义一个全局变量,模拟商品总数
    private static int count = 20;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 使用分布式锁
     * 循环100次,创建100个线程进行模拟下单,当个数为0时,抛出异常终止程序   
     */
    public String testRedisSon() {
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    RLock lock = redissonClient.getLock("test-lock");
                    try {
                        if (lock.tryLock(1000, 1000, TimeUnit.SECONDS)) {
                            if (count <= 0) {
                                throw new RuntimeException("商品已经卖完了,下次再来吧!");
                            }
                            System.out.println("count的值:" + count--);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }
            });
            thread.start();
        }
        return "success";
    }
}

以上就完成了redis的整合与分布式锁redisson的整合与测试!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值