Redis基础(三)—Java中操作redis实践

一、准备工作

1、创建工程

创建maven父工程,例如03-sca-redis,并在此工程下创建两个子工程,一个为sca-jedis,一个为sca-template,例如:
在这里插入图片描述

2、添加项目依赖

2.1)sca-jedis 工程依赖
<dependencies>
<!--jedis依赖(主要依赖)-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.5.2</version>
</dependency>

<!--junit依赖(单元测试)-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<!--Gson依赖(json数据材质)json串-->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>
</dependencies>
2.2)添加sca-template工程依赖
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.2.RELEASE</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

二、Jedis的应用

1、简介

Jedis是Java中操作redis的一个客户端,类似通过jdbc访问mysql数据库。

2、准备工作

2.1)第一步:从redis.io官方下载对应版本的redis.conf文件,地址如下(假如下载不下来从code上去取或者从同学那拿):
https://redis.io/topics/config/
2.2)第二步:停止redis并删除挂载目录下(/usr/local/docker/redis01/conf)的redis.conf配置文件。
2.3)第三步:将下载的redis.conf文件拷贝到redis挂载目录(/usr/local/docker/redis01/conf)

在这里插入图片描述

2.4)第四步:基于vim打开redis.conf文件,然后注释 bind 127.0.0.1这一行,并修改protected-mode的值修改为no。

在这里插入图片描述
在这里插入图片描述

2.5)第五步:重启redis服务,并检查启动日志(docker logs 容器id)

在这里插入图片描述

3、快速入门实现

在Jedis工程中定义单元测试类,在类中定义单元测试方法:

3.1)基础类型操作

在项目的src/test/java目录创建单元测类,例如:

package com.jt;

import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

public class JedisTests {

    @Test
    public void testGetConnection(){
        //假如不能连通,要注释掉redis.conf中 bind 127.0.0.1,
        //并将protected-mode的值修改为no,然后重启redis再试
        Jedis jedis=new Jedis("192.168.64.128",6379);
        //jedis.auth("123456");//假如在redis.conf中设置了密码
        String ping = jedis.ping();
        System.out.println(ping);
    }

在这里插入图片描述

3.1.1)字符串类型练习
    //字符串类型练习
    @Test
    public void testStringOper() throws InterruptedException {
        //1.建立链接(与redis建立链接)
        Jedis jedis=new Jedis("192.168.64.128",6379);
        
        //2.存储数据(key/value)
        jedis.set("count","1");
        jedis.set("id","10001");
        jedis.set("content","aaaaaaaadfas");
        
        //3.更新数据
        jedis.expire("id",1);//设置key的有效时长,1秒
        jedis.incr("count");//对key的值进行自增操作
       
        //4.删除指定数据
        jedis.del("content");

        //5.获取数据
        String count = jedis.get("count");
        //TimeUnit是Java中枚举类型,SECONDS为枚举类型的实例,sleep底层会调用Thread.sleep()方法
        //TimeUnit.SECONDS.sleep(1);//休眠一秒
        Thread.sleep(1000);
        String id=jedis.get("id");
        Long num=jedis.strlen("content");
        System.out.println("cart.count="+count);
        System.out.println("id="+id);
        System.out.println("num="+num);
        String result=String.format("id=%s,content=%s,count=%s",id,content,count);
        System.out.println(result);
        
        //6.释放资源
        jedis.close();
    }

在这里插入图片描述

3.1.2)将一个对象(例如map)转换为json格式字符串,然后写入到redis
    /**
     *将一个对象(例如map)转换为json格式字符串,然后写入到redis
     * */
@Test
 public void testJsonOper(){
 	//1.建立连接
     Jedis jedis=new Jedis("192.168.126.130",6379);
     //2.构建一个map对象,存储一些用户信息
      Map<String,Object> map=new HashMap<>();
      map.put("id",100);
      map.put("title","spring 认证");
      map.put("content","very good");
     
     //3.将对象转换为json格式字符串
      Gson gson=new Gson();
      String jsonStr=gson.toJson(map);
      //4.将json字符串写入到redis
      Jedis jedis=new Jedis("192.168.64.128",6379);
      jedis.set("user",jsonStr);
      //5.读取redis中数据
      jsonStr=jedis.get("user");
      System.out.println(jsonStr);
      Map<String,Object> obj=gson.fromJson(jsonStr,Map.class);
      System.out.println(obj);
      //6.释放资源
      jedis.close();
 }

在这里插入图片描述

3.1.3)Hash类型数据的操作实践
 /**
     * Hash类型数据的操作实践
     */
    @Test
    public void testHashOper01(){
        //1.建立连接
        Jedis jedis=new Jedis("192.168.64.128",6379);
        //2.基于hash类型存储对象信息
        jedis.hset("member","id","101");
        jedis.hset("member","username","jack");
        jedis.hset("member","mobile","3333333");
        //3.更新hash类型存储的数据
        jedis.hset("member","username","tony");
        //4.获取hash类型数据信息
        String username=jedis.hget("member","username");
        String mobile = jedis.hget("member", "mobile");
        System.out.println(username);
        System.out.println(mobile);
        //5.释放资源
        jedis.close();
    }

在这里插入图片描述

3.1.4)hash类型练习(直接存储map对象)
//hash类型练习(直接存储map对象)
@Test
public void testHashOper02(){
    //1.建立连接
    Jedis jedis=new Jedis("192.168.64.128",6379);
    //2.存储一篇博客信息
    Map<String,String> map=new HashMap<>();
    map.put("x","100");
    map.put("y","200");
    jedis.hset("point",map);
    //3.获取博客内容并输出
    map=jedis.hgetAll("point");
    System.out.println(map);
    //4.释放资源
    jedis.close();
}

在这里插入图片描述

3.1.5)基于FIFO(First In First Out)(先进先出)算法,借助redis实现一个队列
  /**
     * 测试:redis中list结构的应用
     * 基于FIFO(First In First Out)算法,借助redis实现一个队列
     */
    @Test
    public void testListOper01(){
        //1.建立连接
        Jedis jedis=new Jedis("192.168.64.128",6379);
        //2.存储数据
        jedis.lpush("lst1","A","B","C","C");
        //3.更新数据
        Long pos=jedis.lpos("lst1","A");//获取A元素的位置
        jedis.lset("lst1",pos,"D");//将A元素位置的内容修改为D
        //4.获取数据
        int len=jedis.llen("lst1").intValue();//获取lst1列表中元素个数
        List<String> rpop = jedis.rpop("lst1",len);//获取lst1列表中所有元素
        System.out.println(rpop);
        //5.释放资源
        jedis.close();
    }

在这里插入图片描述

3.1.6)list类型练习:实现一个阻塞式队列

==
brpop意思 block right pop 阻塞式右侧出队
blpop意思 block left pop 阻塞式左侧出队
第一个要出队的Key,第二个是Timeout 阻塞延时,如果填写0,那么默认是永久阻塞,当List有值的时候,会立刻pop出来==

    /**
     * 阻塞式队列,brpop/blpop
     */
    @Test
    public void testListOper02(){
        System.out.println(Thread.currentThread().getName()); //获取当前线程的名字
        //1.建立连接
        Jedis jedis=new Jedis("192.168.64.128",6379);
        //2.存储数据
        jedis.lpush("lst2","A","B","C");
        //3.取数据(队列为空则阻塞)
        //第一个要出队的Key,第二个是Timeout 阻塞延时,如果填写0,那么默认是永久阻塞,当List有值的时候,会立刻pop出来
        jedis.brpop(5,"lst2");
        jedis.brpop(5,"lst2");
        jedis.brpop(5,"lst2");
        jedis.brpop(5,"lst2");//当队列中没有内容时会阻塞
        System.out.println("waiting finish");
        //4.释放资源
        jedis.close();
    }

在这里插入图片描述

3.1.7)set类型练习
/**
     * Set数据类型测试
     */
    @Test
    public void testSetOper01(){
        //1.建立连接
        Jedis jedis=new Jedis("192.168.64.128",6379);//TCP/IP
        //2.存储数据(不允许重复,且值无序)
        jedis.sadd("set01","A","A","B","B","C");
        //3.删除集合中元素
        jedis.srem("set01","A");
        //4.获取存储的数据
        System.out.println(jedis.scard("set01"));//集合元素的个数
        Set<String> set01 = jedis.smembers("set01");//输出集合中的成员 (点赞的成员)
        System.out.println(set01);
        //5.释放资源
        jedis.close();
    }

在这里插入图片描述

3.2)连接池JedisPool应用

我们直接基于Jedis访问redis时,每次获取连接,释放连接会带来很大的性能开销,可以借助Jedis连接池,重用创建好的连接,来提高其性能,简易应用方式如下:

package com.jt;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


public class JedisPoolTests {
    @Test
   public void testJedisPool(){
        //1.定义连接池的配置
        JedisPoolConfig config=new JedisPoolConfig();
        config.setMaxTotal(1000);//最大连接数
        config.setMaxIdle(60);//最大空闲时间(连接不用了要释放)
        //2.创建连接池
        JedisPool jedisPool=
        new JedisPool(config,"192.168.64.128",6379);
        //3.从池中获取一个连接
        Jedis resource = jedisPool.getResource();
        resource.auth("123456");
        //4.通过jedis连接存取数据
        resource.set("class","cgb2004");
        String clazz=resource.get("class");
        System.out.println(clazz);
        //5. 将链接返回池中
        resource.close();
        //关闭连接池
        jedisPool.close();
    }
}

在这里插入图片描述

三、RedisTemplate应用

1、简介

RedisTemplate为SpringBoot工程中操作redis数据库的一个Java对象,此对象封装了对redis的一些基本操作。

2、准备工作

2.1)第一步:创建工程配置文件application.yml,其内容如下:
spring:
  redis:
    host: 192.168.64.128  #写自己的ip
    port: 6379

2.2)第二步:创建工程启动类,例如:
package com.jt;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RedisApplication {
    public static void main(String[] args) {
        SpringApplication.run(RedisApplication.class,args);
    }
}

3、快速入门实现

3.1)StringRedisTemplate 应用

StringRedisTemplate 是一个专门用于操作redis字符串类型数据的一个对象,其应用方式如下:

3.1.1)连接redis服务器测试
package com.jt.redis;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
public class StringRedisTemplateTests {
    /**此对象为spring提供的一个用于操作redis数据库中的字符串的一个对象*/
    /**StringRedisTemplate 对象是spring data模块推出的一个用于
     * 操作redis字符串类型数据的一个API对象,底层序列方式使用的是
     * StringRedisSerializer对象
     * */
  @Autowired
  private StringRedisTemplate stringRedisTemplate;
  
  @Test
  void testConnection(){
        RedisConnection connection =
                stringRedisTemplate.getConnectionFactory()
                        .getConnection();
        String ping = connection.ping();
        System.out.println(ping);
    }

在这里插入图片描述

3.1.2)字符串数据基本操作实践
/**
     * 字符串数据基本操作实践
     * @throws InterruptedException
     */
    @Test
    void testStringOper01() throws InterruptedException {
       //1.获取一个操作redis字符串的值对象
        ValueOperations<String, String> vo =
                redisTemplate.opsForValue();
        //2.基于这个值对象操作redis中的字符串数据
        vo.set("x","100");
        vo.increment("x"); //自增,默认自增1
        vo.set("y","200",1, TimeUnit.SECONDS);//设置key的失效时间 ,1秒
        TimeUnit.SECONDS.sleep(1);//阻塞1秒
        String x = vo.get("x");
        System.out.println(x);
        String y=vo.get("y");
        System.out.println(y);
    }

在这里插入图片描述

3.1.3)以json格式存储一个对象到redis数据库
    /**以json格式存储一个对象到redis数据库
     * 提示:不能使用Gson,可以使用jackson*/
    @Test
    void testStringOper02() throws JsonProcessingException {
        //1.创建一个map,用于存储对象数据
        Map<String,String> map=new HashMap<String,String>();
        map.put("id","101");
        map.put("username","jack");
        //2.将map转换为json格式字符串
        String jsonStr =
        new ObjectMapper().writeValueAsString(map);
        					//(需要转换的对象)
        System.out.println(jsonStr);
        //3.将json字符串借助StringRedisTemplate存储到redis,并读取
        ValueOperations<String, String> vo =
                redisTemplate.opsForValue();
        vo.set("userJsonStr",jsonStr);
        jsonStr=vo.get("userJsonStr");
        //4.将json格式的字符串转成map
        map= new ObjectMapper().readValue(jsonStr,Map.class);
        							//(json格式,需要转成的格式)
        System.out.println(map);
    }

在这里插入图片描述

3.1.4)基于StringRedisTemplate对象操作hash数据类型
    /**
     * 基于StringRedisTemplate对象操作hash数据类型
     */
    @Test
    void testHashOper01(){
        //1.获取操作hash类型数据的对象
        HashOperations<String, Object, Object> ho
                = redisTemplate.opsForHash();
        //2.操作hash类型数据
        ho.put("user","id","100");
        ho.put("user","username","jack");
        ho.put("user","state","true");
        List<Object> user = ho.values("user");
        System.out.println(user);
    }

在这里插入图片描述
在这里插入图片描述

3.2)RedisTemplate 应用

RedisTemplate是一个专门用于实现对远端redis中复杂数据的操作的对应,应用案例如下:

package com.jt;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@SpringBootTest
public class RedisTemplateTests {
    /**RedisTemplate对象也Spring data模块提供的一个操作redis数据库数据的API对象,
     * 此对象主要用于操作redis数据库中的复杂数据类型数据,默认序列化方式为
     * JdkSerializationRedisSerializer*/
    @Autowired
    private RedisTemplate redisTemplate;//将来可以按照自己的业务需求定制RedisTempalte

    @Test
    void testSetData(){
        SetOperations setOperations=redisTemplate.opsForSet();
        setOperations.add("setKey1", "A","B","C","C");
        Object members=setOperations.members("setKey1");
        System.out.println("setKeys="+members);
        //........
    }
    @Test
    void testListData(){
        //向list集合放数据
        ListOperations listOperations = redisTemplate.opsForList();
        listOperations.leftPush("lstKey1", "100"); //lpush
        listOperations.leftPushAll("lstKey1", "200","300");
        listOperations.leftPush("lstKey1", "100", "105");
        listOperations.rightPush("lstKey1", "700");
        Object value= listOperations.range("lstKey1", 0, -1);
        System.out.println(value);
        //从list集合取数据
        Object v1=listOperations.leftPop("lstKey1");//lpop
        System.out.println("left.pop.0="+v1);
        value= listOperations.range("lstKey1", 0, -1);
        System.out.println(value);
    }

    @Test
    void testHashOper01(){
        HashOperations ho = redisTemplate.opsForHash();
        ho.put("blog", "id", 101);
        ho.put("blog", "title", "redis template");
        List blog = ho.values("blog");

        System.out.println(blog);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("id", 201);
        map.put("name", "redis");
        ho.putAll("tag",map);
        Object name= ho.get("tag", "name");
        System.out.println(name);
    }

    @Test
    void testStringOper01(){
        //默认采用了JDK的序列化方式,存储key/value默认会将key/value都转换为字节再进行存储
        //redisTemplate.setKeySerializer(new JdkSerializationRedisSerializer());

        //自己设置序列化方式
        //redisTemplate.setKeySerializer(new StringRedisSerializer());
        //redisTemplate.setValueSerializer(new StringRedisSerializer());
        ValueOperations vo =
                redisTemplate.opsForValue();
        vo.set("token", UUID.randomUUID().toString());
        Object token = vo.get("token");
        System.out.println(token);
    }
}

3.3)定制RedisTemplate对象(拓展)

对于系统默认的RedisTemplate默认采用的是JDK的序列化机制,假如我们不希望实用JDK的序列化,可以采用的定制RedisTemplate,并采用自己指定的的序列化方式,例如:

package com.jt.redis.config;
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        //1.构建RedisTemplate对象
        RedisTemplate<Object,Object> redisTemplate=new RedisTemplate<>();
        //2.设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //3.定义序列化方式(在这里选择jackson)
        Jackson2JsonRedisSerializer redisSerializer= new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper=new ObjectMapper();
        //设置要序列化的域(属性)
        //any表示任意级别访问修饰符修饰的属性 private,public,protected
        objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        //启动输入域检查(类不能是final修饰的)
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY);
        redisSerializer.setObjectMapper(objectMapper);
        //4.设置RedisTemplate的序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(redisSerializer);
        //spring规范中假如修改bean对象的默认特性,建议调用一下afterPropertiesSet()
        redisTemplate.afterPropertiesSet();
       return redisTemplate;
    }
}

创建Blog对象,然后基于RedisTemplate进行序列化实践,Blog代码如下:

package com.jt.redis.pojo;

import java.io.Serializable;

public class Blog implements Serializable {//{"id":10,"title":"redis"}
    private static final long serialVersionUID = -6721670401642138021L;
    private Integer id;
    private String title;
    public Blog(){
        System.out.println("Blog()");
    }
    public Blog(Integer id,String title){
        this.id=id;
        this.title=title;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
    @Override
    public String toString() {
        return "Blog{" +
                "id=" + id +
                ", title='" + title + '\'' +
                '}';
    }
}

四、项目工程实践

1、单点登陆

1.1)业务描述

在分布式系统中,通过会有多个服务,我们登录了一个服务以后,再访问其它服务时,不想再登录,就需要有一套单独的认证系统,我们通常会称之为单点登录系统,在这套系统中提供一个认证服务器,服务完成用户身份认证,在一些中小型分布式系统中,我们通常会借助redis存储用户的认证信息,例如:

在这里插入图片描述

1.2)关键代码实现
package com.jt.demos;

import redis.clients.jedis.Jedis;

import java.util.UUID;

/**
 * 单点登录应用实践
 */
public class SSODemo01 {
    static String token;
    //模仿访问服务端的资源
    static void doGetResource(){
        //1.检查token是否存在,(token是存储在客户端-Cookie,localStorage)
        if(token==null){
            System.out.println("please login");
            return;
        }
        //2.检查token是否已经失效
        Jedis jedis=new Jedis("192.168.64.128",6379);
        String user = jedis.get(token);
        jedis.close();
        if(user==null){
            System.out.println("login timeout or token invalid");
            return;
        }
        //3.返回你要访问的资源
        System.out.println("return user resource");
    }
    static void doLogin(String username,String password){
        if("jack".equals(username)&&"123456".equals(password)){
            System.out.println("login ok");
            String token= UUID.randomUUID().toString();
            Jedis jedis=new Jedis("192.168.64.128",6379);
            jedis.set(token,username);//存储用户信息
            jedis.expire(token,1); //token有效期是1秒
            jedis.close();
            //将token存储到客户端
            SSODemo01.token=token;
            return;
        }
        System.out.println("username or password error");
    }
    public static void main(String[] args) throws InterruptedException {//这里的main方法代表客户端
        //1.访问资源
        doGetResource();
        //2.执行登录操作
        doLogin("jack","123456");
        //3.再次访问资源
        Thread.sleep(1000);
        doGetResource();
    }
}

在这里插入图片描述

2、投票系统

2.1)业务描述

在很多系统中设计中,都会有一个活动设计,开启一个活动之前,可以对这个活动的支持力度先进行一个调查,例如基于这个活动设计一个投票系统,例如:
在这里插入图片描述

2.2)关键代码实现
package com.jt.demos;

import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * 投票系统演示:模拟基于某个活动的投票程序
 * 业务说明:一个用户只能投票一次(不允许重复)
 * 数据结构设计:基于redis的set类型进行数据存储
 */
public class VoteDemo01 {

    //注意,将来这个连接不能多线程共享
    private static Jedis jedis=new Jedis("192.168.126.130",6379);

    /**
     * 判定userId是否参与过activityId这个活动的投票
     * @param activityId
     * @param userId
     * @return true表示参与过投票
     */

    static boolean checkVote(String activityId,String userId){
        //判断set集合activityId对应的值中是否包含这个userId
       return jedis.sismember(activityId,userId);
    }

    /**
     * 执行投票逻辑
     * @param activityId
     * @param userId
     * @return true 表示投票ok
     */
    static boolean addVote(String activityId,String userId){
        if(checkVote(activityId,userId)){
            System.out.println("您已经参与过这个投票");
            return false;
        }
        jedis.sadd(activityId,userId);
        return true;
    }

    /**
     * 获取活动的总票数
     * @param activityId
     * @return
     */
    static Long getActivityVotes(String activityId){
        return jedis.scard(activityId);
    }
    /**
     * 获取参与了投票的用户id
     * @param activityId
     * @return
     */
    static Set<String>  getActivityUsers(String activityId){
       return jedis.smembers(activityId);
    }

    public static void main(String[] args) {
        //1.设置一个活动
        //1)获取id
        String activityId="10001";
        //2)活动标题
        //3)活动内容
        //2.基于活动进行投票设计
        String user1="201";
        String user2="202";
        String user3="203";
        //2.1 一个用户对同一个活动不能重复投票
        //boolean flag=checkVote(activityId,user1);
        //System.out.println("flag="+flag);
        //2.2 执行投票
        addVote(activityId,user1);
        addVote(activityId,user2);
        addVote(activityId,user3);
        //2.3 能够显示参与投票的人数
        long voteCount=getActivityVotes(activityId);
        System.out.println(voteCount);
        //2.4 管理员可以查看哪些人参与了投票
        Set<String> userIds=getActivityUsers(activityId);
        System.out.println(userIds);
    }
}

在这里插入图片描述

3、秒杀队列

3.1)业务描述

在设计一个秒杀或抢购系统时,为了提高系统的响应速度,通常会将用户的秒杀或抢购请求先存储到一个redis队列,这里我们就基于redis实现一个先进先出队列,例如:
在这里插入图片描述

3.2)关键代码实现
3.2.1)jedis写法
package com.jt.demos;

import redis.clients.jedis.Jedis;

//秒杀队列演示
//描述逻辑中会将商品抢购信息先写到redis(以队列形式进行存储),
//因为写redis内存数据库要比写你的mysql数据库快很多倍
//算法:先进先出(FIFO)-体现公平性
public class SecondKillDemo01 {

    //商品抢购首先是入队
    static void enque(String msg){//入队
         Jedis jedis=new Jedis("192.168.64.128",6379);
         jedis.auth("123456");//没有认证不需要写这个语句
         jedis.lpush("queue",msg);
         jedis.close();
    }

    //底层异步出队(基于这个消息,生成订单,扣减库存,...)
    static String deque(){//出队
        Jedis jedis=new Jedis("192.168.64.128",6379);
        jedis.auth("123456");//没有认证不需要写这个语句
        String result=jedis.rpop("queue");
        jedis.close();
        return result;
    }
    public static void main(String[] args){
        //1.多次抢购(模拟在界面上多次点击操作)
        new Thread(){
            @Override
            public void run() {
                for(int i=1;i<=10;i++){//模拟页面上按钮点击
                    enque(String.valueOf(i));
                    try{Thread.sleep(100);}catch(Exception e){}
                }
            }
        }.start();

        //2.从队列取内容(模拟后台从队列取数据)
        new Thread(){
            @Override
            public void run() {
                for(;;){
                    String msg=deque();
                    if(msg==null)continue;
                    System.out.print(msg);
                }
            }
        }.start();

    }
}

3.2.2)RedisTemplate写法
package com.jt.redis.demos;

import org.springframework.data.redis.core.ListOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * 定义一个简易的秒杀队列,算法FIFO
 */
//@Component
@Repository //@Repository 注解用于描述数据层对象
public class SecondKillQueue {
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    //这种写法:参考官网https://spring.io/projects/spring-data-redis#overview
    @Resource(name = "stringRedisTemplate")
    private ListOperations<String,String> lo;

    /**执行入队操作*/
    public void enque(String msg){
//        ListOperations<String, String> lo =
//                stringRedisTemplate.opsForList();
        lo.leftPush("killQueue", msg);
    }
    /**执行出队操作*/
    public String deque(){
//        ListOperations<String, String> lo =
//                stringRedisTemplate.opsForList();
        return lo.rightPop("killQueue");
    }
}
package com.jt;

import com.jt.redis.demos.SecondKillQueue;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class SecondKillQueueTests {
    @Autowired
    private SecondKillQueue queue;
    @Test
    void testEnque(){
       queue.enque("A");
       queue.enque("B");
       queue.enque("C");
    }
    @Test
    void testDeque(){
        System.out.println(queue.deque());
        System.out.println(queue.deque());
        System.out.println(queue.deque());
    }
}

4、分布式id

4.1)业务描述

在分布式系统中,数据量将越来越大时,就需要对数据进行分表操作,但是,分表后,每个表中的数据都会按自己的节奏进行自增,很有可能出现ID冲突。这时就需要一个单独的机制来负责生成唯一ID,生成出来的ID也可以叫做 分布式ID,这里我们借助redis实现一个简易的分布式id进行实现,当然还有一些第三方的系统,可以帮你生成这样的id,可以自己进行拓展学习。

4.2)关键代码实现
4.2.1)Jedis写法
package com.jt.demos;

import redis.clients.jedis.Jedis;

/**
 * 需求:生成一个分布递增的id
 * 多张表基于这个方法中生成的id作为主键id值(分布式环境不会采用数据库
 * 表中自带的自增策略-auto_increment)
 */
public class IdGeneratorDemo01 {
    public static Long getId(){
          Jedis jedis=new Jedis("192.168.64.128",6379);
          jedis.auth("123456");
          Long id = jedis.incr("id");
          jedis.close();
          return id;
    }
    public static void main(String[] args) {
         for(int i=0;i<10;i++) {
              new Thread(){
                  @Override
                  public void run() {
                      String tName=Thread.currentThread().getName();
                      System.out.println(tName+"->"+
                              IdGeneratorDemo01.getId());
                  }
              }.start();
          }

    }
}

4.2.2)RedisTemplate写法
package com.jt.redis.demos;

import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class IdGenerator {
    @Resource(name = "stringRedisTemplate")
    private ValueOperations valueOperations;
    /**基于redis生成一个递增的id值*/
    public Long generatorId(){
        return valueOperations.increment("id");
    }
}
package com.jt;

import com.jt.redis.demos.IdGenerator;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class IdGeneratorTests {
    @Autowired
    private IdGenerator idGenerator;
    @Test
    void doGeneratorId(){
        for(int i=0;i<10;i++){
            new Thread(()->{
                System.out.println(idGenerator.generatorId());
                System.out.println(idGenerator.generatorId());
                System.out.println(idGenerator.generatorId());
            }).start();
        }
        while(true){}//等new的线程执行结束
    }
}

5、购物车简易实现

5.1)业务描述

简易购物车业务设计如图所示:
在这里插入图片描述

5.2)基础指令操作,例如:
1)向购物车添加商品
hset  cart:101  2001  1
hset  cart:101  2002  1
hset  cart:101  2003  2

2)查看购物车商品
hgetall cart:101

3)删除购物车商品
hdel cart:101 2003

4)改变购物车某个商品的购买数量
hincrby cart:101 2002 2

5.3)关键代码实现
5.3.1)Jedis写法
package com.jt.demos;

import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * 作业:基于redis存储商品购物车信息
 */
public class CartDemo01 {

    public static void addCart(Long userId,Long productId,int num){
        //1.建立redis链接
        Jedis jedis=new Jedis("192.168.64.128",6379);
        jedis.auth("123456");
        //2.向购物车添加商品
        //hincrBy这个函数在key不存在时会自动创建key
        jedis.hincrBy("cart:" + userId, String.valueOf(productId),num);
        //3.释放redis链接
        jedis.close();
    }
    //查看我的购物车
    public static Map<String, String> listCart(Long userId){
        //1.建立redis链接
        Jedis jedis=new Jedis("192.168.64.128",6379);
        jedis.auth("123456");
        //2.查看购物车商品
        Map<String, String> map = jedis.hgetAll("cart:" + userId);
        //3.释放redis链接
        jedis.close();
        return map;
    }
    public static void main(String[] args) {
        //1.向购物车添加商品
        addCart(101L,201L,1);
        addCart(101L,202L,1);
        addCart(101L,203L,2);
        //2.查看购物车商品
        Map<String, String> map = listCart(101L);
        System.out.println(map);
    }

}
5.3.2)RedisTemplate写法
package com.jt.redis.demos;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 向购物车添加数据
     */
    public void addCart(Integer userId,String productId,int num){
        HashOperations hashOperations = redisTemplate.opsForHash();
        //key不存在则会自动创建
        hashOperations.increment("cart:"+userId, productId, num);
    }
    /**
     * 查看购物车商品
     * @param userId
     * @return
     */
    public Map<String,Object> listCart(Integer userId){
        HashOperations hashOperations = redisTemplate.opsForHash();
        return hashOperations.entries("cart:"+userId);
    }

}

package com.jt;

import com.jt.redis.demos.CartService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Map;

@SpringBootTest
public class CartServiceTests {

    @Autowired
    private CartService cartService;

    @Test
    void testAddCart(){
        cartService.addCart(101, "201", 1);
        cartService.addCart(101, "201", 2);
    }
    @Test
    void testListCart(){
        Map<String, Object> stringObjectMap =
                cartService.listCart(101);
        System.out.println(stringObjectMap);
    }
}

定制序列化方式

package com.jt.redis.demos;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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;

//定制序列化
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        //1.构建RedisTemplate对象
        RedisTemplate<Object,Object> redisTemplate=new RedisTemplate<Object,Object>();
        //2.设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //3.定义序列化方式(在这里选择jackson)
        Jackson2JsonRedisSerializer redisSerializer= new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper=new ObjectMapper();
        //设置要序列化的域(属性)
        //any表示任意级别访问修饰符修饰的属性 private,public,protected
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //启动输入域检查(类不能是final修饰的)
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY);
        redisSerializer.setObjectMapper(objectMapper);
        //4.设置RedisTemplate的序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(redisSerializer);
        //spring规范中假如修改bean对象的默认特性,建议调用一下afterPropertiesSet()
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

5.3.3 注解的方式,自定义序列化方式
package com.jt.redis.demos;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Resource(name = "stringRedisTemplate") //注解的方式,定制序列化方式
    private HashOperations hashOperations;

    /**
     * 向购物车添加数据
     */
    public void addCart(Integer userId,String productId,int num){
        //HashOperations hashOperations = redisTemplate.opsForHash();
        //key不存在则会自动创建
        hashOperations.increment("cart:"+userId, productId, num);
    }
    /**
     * 查看购物车商品
     * @param userId
     * @return
     */
    public Map<String,Object> listCart(Integer userId){
        //HashOperations hashOperations = redisTemplate.opsForHash();
        return hashOperations.entries("cart:"+userId);
    }

}

6、登录验证码实践

6.1)业务描述

1)进入登录页面之前先创建一个验证码,并将其存储在redis中
2)登录时输入验证码,并且将验证码与redis中的验证码进行比对

6.2)关键代码实现
package com.jt.demos;

import redis.clients.jedis.Jedis;

/**登录验证码实践
 * 1)进入登录页面之前先创建一个验证码,并将其存储在redis中
 * 2)登录时输入验证码,并且将验证码与redis中的验证码进行比对
 * */
public class CodeDemo01 {
    static void doLogin(String username,String password,String inputCode){
       //1.校验验证码
        //1.1验证是否为空
       if(inputCode==null||"".equals(inputCode)){
           System.out.println("please input code");
           return;
       }
       //1.2验证redis中的code
       Jedis jedis=new Jedis("192.168.126.130",6379);
       String dbCode=jedis.get("code");
       if(dbCode==null){
           System.out.println("code timeout");
           return;
       }
       if(!inputCode.equals(dbCode)){
           System.out.println("code error");
           return;
       }
       //2......
       System.out.println("继续验证用户身份合法性");
    }
    public static void main(String[] args) {
        char[] chars={
                'A','B','C','D','1','2','.'
        };//后续可以写一个算法从这个数组中随机取出四个值
       //1.生成一个随机验证码
        String code="12AB";
        Jedis jedis=new Jedis("192.168.64.128",6379);
        jedis.set("code","12AB");
        jedis.expire("code",60);
        jedis.close();
       //2.执行登录操作
        doLogin("jack","123456","12AB");
    }
}

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Redis是一个开源的内存数据结构存储系统,常用于缓存、消息队列和数据库。在Java连接Redis可以使用Jedis驱动包\[1\]。下面是一些基本的Redis Java操作示例: 1. 字符串操作: ```java Jedis jedis = new Jedis("localhost", 6379); jedis.set("username", "zhangsan"); // 设置键值对 String username = jedis.get("username"); // 获取值 Long deleted = jedis.del("username"); // 删除键值对 jedis.close(); ``` 2. 哈希操作: ```java Jedis jedis = new Jedis("localhost", 6379); jedis.hset("user", "name", "John"); // 设置哈希字段 String name = jedis.hget("user", "name"); // 获取哈希字段的值 Long deleted = jedis.hdel("user", "name"); // 删除哈希字段 jedis.close(); ``` 除了字符串和哈希操作Redis还支持列表、集合和有序集合等数据结构的操作。你可以根据具体需求选择适合的操作方法\[3\]。 #### 引用[.reference_title] - *1* [Java开发Redis的基本操作](https://blog.csdn.net/m0_67094505/article/details/127605008)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [RedisJava操作redis实践](https://blog.csdn.net/weixin_55026035/article/details/124220266)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Java-Redis基本使用大全](https://blog.csdn.net/weixin_45203607/article/details/120235597)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AimerDaniil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值