• Redis_03_Java Jadis实现事务和乐观锁


    1.Jedis是Redis官方推荐的Java连接开发工具。要在Java开发中使用好Redis中间件,必须对Jedis熟悉才能写成漂亮的代码

    1.连接测试

    pom.xml

            <!--jedis-->
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
                <version>3.2.0</version>
            </dependency>
            <!--fastjson-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.75</version>
            </dependency>
    public class RedisStringJava {
        public static void main(String[] args) {
            //连接本地的 Redis 服务
            Jedis jedis = new Jedis("47.100.***.***", 6379);
             System.out.println(jedis.ping());
        }
    }

    2.Jedis事务的实现

    public class RedisTx {
        public static void main(String[] args) {
    
            Jedis jedis = new Jedis("47.100.***.***", 6379);
            jedis.flushAll();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("age", 20);
            jsonObject.put("name", "哈哈");
    
            String res = jsonObject.toJSONString();
            //监听jedis 乐观锁实现
            jedis.watch(res);
            //开启事务
            Transaction transaction = jedis.multi();
            try {
                Response<String> user = transaction.set("user", res);
                //发生异常事务回滚
                int a = 1 / 0;
    //提交事务 transaction.exec(); }
    catch (Exception e) {
    //回滚 transaction.discard(); }
    finally { System.out.println(jedis.get("user")); jedis.close(); } }

     3.redis实现分布式锁

  • 相关阅读:
    spring boot自动配置
    servlet类与Spring Controller类的关系
    Junit中的setup和teardown方法
    dependency的scope
    mapper的namespace
    mybatis缓存
    Ehcache(05)——缓存的查询
    Ehcache(04)——设置缓存的大小
    Ehcache(03)——Ehcache中储存缓存的方式
    Ehcache(02)——ehcache.xml简介
  • 原文地址:https://www.cnblogs.com/asndxj/p/14263157.html
Copyright © 2020-2023  润新知