redis(11):springboot中使用redis

1 创建springboot项目

2 创建pom文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3 创建application.yml

复制代码
#redis的配置
spring:
  redis:
    host: 192.168.222.131
    password: 123456
    port: 6379
    jedis:
      pool:
        max-active: 20
        max-idle: 8
        min-idle: 0
        max-wait: 2000

4 测试StringRedisTemplate

复制代码
package com.example.demo;

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

import java.util.Collection;
import java.util.List;

@SpringBootTest
class ApplicationTests {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        System.out.println(redisTemplate);
    }

    @Test
    void flushdb(){
        redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushAll();
                connection.flushDb();
                return "ok";
            }
        });
    }

    @Test
    void testNormal(){
        redisTemplate.keys("*");
        redisTemplate.multi();
        redisTemplate.exec();
        redisTemplate.watch("");
        redisTemplate.unwatch();
        redisTemplate.delete("k1");
        Collection<String> keys=null;
        redisTemplate.delete(keys);
        redisTemplate.randomKey();
        redisTemplate.rename("oldKey","newKey");
        redisTemplate.discard();

        //
        redisTemplate.getStringSerializer(); //指redis key序列化方式
        redisTemplate.getValueSerializer();  //指值的序列化方式
        redisTemplate.getHashKeySerializer();//指hash  Vlaue的 key序列化方式  hset(key,key,value)
        redisTemplate.getHashValueSerializer();//指hash  Vlaue的 value序列化方式


    }

    @Test
    void testString(){
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        //System.out.println(redisTemplate.getKeySerializer());
        //System.out.println(redisTemplate.getValueSerializer());

        //其它方法集
        RedisOperations<String, String> operations = opsForValue.getOperations();
//        opsForValue.get("");
//        opsForValue.set("","");
//        opsForValue.setIfPresent("","");
//        opsForValue.increment("");
//        opsForValue.decrement("");
//        opsForValue.set("name","xiaoming");
        System.out.println(opsForValue.get("name"));
        System.out.println("--------------------------");

        System.out.println("操作完成");
    }

    @Test
    void testList(){
        ListOperations<String, String> opsForList = this.redisTemplate.opsForList();

        RedisOperations<String, String> operations = opsForList.getOperations();

        opsForList.leftPush("","");
        opsForList.leftPushAll("","","","");
        opsForList.rightPush("","");
        opsForList.rightPushAll("","");
        opsForList.leftPop("");
        opsForList.rightPop("");


        List<String> key = opsForList.range("key", 0, -1);

    }

    @Test
    void testHash(){
        HashOperations<String, Object, Object> opsForHash = this.redisTemplate.opsForHash();

        opsForHash.put("","hashKey","value");

        opsForHash.get("","hashKey");

    }

    @Test
    void testSet(){
        SetOperations<String, String> opsForSet = this.redisTemplate.opsForSet();
        opsForSet.add("","");
        opsForSet.members("");

    }

    @Test
    void testZset(){
        ZSetOperations<String, String> opsForZSet = this.redisTemplate.opsForZSet();
        opsForZSet.add("key","value",1);

    }


    /**
     * 集群操作
     */
    @Test
    void test(){
        ClusterOperations<String, String> clusterOperations = this.redisTemplate.opsForCluster();
    }

}

5 创建User

复制代码
package com.example.demo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private Integer id;
    private String name;
    private String address;
    private Date brith;
}

6 测试RedisTemplate<Object,Object>

序列化接口

若不设置序列化规则,它将使用JDK自动的序列化将对象转换为字节,存到Redis 里面

它可以存在对象到redis里面

如果对象没有序列化,那么默认使用的JDK的序列化方式

复制代码
package com.example.demo;

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.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Date;

@SpringBootTest
class ApplicationRedisTemplateTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        System.out.println(redisTemplate);
        System.out.println(redisTemplate.getKeySerializer());
        System.out.println(redisTemplate.getValueSerializer());
    }
    @Test
    void testString(){
        //这是设置key的序列化方式   因为RedisTemplate<Object,Object> 如果传String key会被当做object进么序列化
        this.redisTemplate.setKeySerializer(new StringRedisSerializer());
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set("user:1".toString(),new User(1,"xiaoming","wh",new Date()));
        User user = (User) opsForValue.get("user:1");
        System.out.println(user);
        System.out.println("操作成功");
    }
    @Test
    void testString2(){
        //这是设置key的序列化方式   因为RedisTemplate<Object,Object> 如果传String key会被当做object进么序列化
        this.redisTemplate.setKeySerializer(new StringRedisSerializer());
        this.redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        ValueOperations opsForValue = redisTemplate.opsForValue();
        //opsForValue.set("user:2".toString(),new User(1,"xiaoming","wh",new Date()));
        User user = (User) opsForValue.get("user:2");
        System.out.println(user);
        System.out.println("操作成功");
    }
}
相关推荐
Java&Develop8 分钟前
IDEA报错:前言中不允许有内容
java
软件架构师-叶秋11 分钟前
spring boot入门篇之开发环境搭建
java·spring boot·后端
技术砖家--Felix11 分钟前
Spring Boot Web开发篇:构建RESTful API
前端·spring boot·restful
无敌最俊朗@34 分钟前
SQLite 约束 (Constraints) 面试核心知识点
java·开发语言·jvm
憨憨崽&1 小时前
C语言、Java、Python 的选择与未来发展以及学习路线
java·c语言·python
在坚持一下我可没意见1 小时前
Java 网络编程:TCP 与 UDP 的「通信江湖」(基于UDP回显服务器)
java·服务器·开发语言·tcp/ip·udp·java-ee
少爷晚安。1 小时前
Java零基础学习完整笔记,基于Intellij IDEA开发工具,笔记持续更新中
java·笔记·学习
悟能不能悟2 小时前
在service方法中已经catch异常,Transactional失效怎么办
java·数据库·sql
西红柿维生素2 小时前
23种设计模式-框架中的使用
java·开发语言·设计模式
日月星辰Ace2 小时前
JDK 工具学习系列(一):javac、java 命令与 main 方法详解
java