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

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

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.redisson
            redisson
            ${redisson.version}
        

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 redisTemplate = new RedisTemplate();
        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是:

        
            org.redisson
            redisson
            ${redisson.version}
        

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的整合与测试!

你可能感兴趣的:(redis,redis,java,分布式)