Spring boot simple connection redis

Notice

When testing the effect, the automatic injection may report red at this time

Replace @Autowired with @Resource

 

The difference between @Autowired and @Resource

The common point
@Resource and @Autowired are both used for bean injection.

difference

Autowired is injected according to type assembly by default. By default, it requires that dependent objects must exist

Resource is assembled and injected by name by default. Only when no bean matching the name can be found will it be assembled and injected by type
 


foreword

Two ways for java to connect to redis

1. Directly connect to
  Jedis jedis = new Jedis("192.168.223.211",6379);
  if there is a password: jedis.auth("123456");
  then you can operate Redis
 
2. Connection pool connection (connection pool remember: Close resources)
  //Jedis related configuration information
  JedisPoolConfig config = new JedisPoolConfig();
  config.setMaxTotal(500);
  config.setMaxIdle(5);
  config.setMaxWaitMillis(1000 * 100);
  config.setTestOnBorrow(true);
  //redis The connection pool connection is successful
  JedisPool pool = new JedisPool(config, "192.168.223.211", 6379, timeout, "123456");
  //Get a connection in the connection pool
  Jedis jedis = pool.getResource();
  Then you can Redis is operating


1. How to start redis after setting the password

use 

redis-cli -p 6379 -a 123456 

start up

2. Environment preparation and testing

Start the redis service first

Create a project and introduce dependencies

  <!--redis连接jar包-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.6.0</version>
        </dependency>

        <!--spring boot整合redis的主启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

Configure application.yml

spring:
  redis:
    #数据库索引,默认为0
    database: 0
    #redis host ip
    host: 192.168.91.129
    #redis  连接端口
    port: 6379
    #服务器连接密码(默认为空)
    password: 123456
    #连接超时时间(毫秒)
    timeout: 1000
    jedis:
      #连接池配置
      pool:
        #连接池最大连接数
        max-active: 8
        #连接池最大阻塞等待时间(负值表示没有限制)
        max-wait: 5000
        #连接池最大空闲连接
        max-idle: 8
        #连接池最小空闲连接
        min-idl: 0

configuration complete

test use


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.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@SpringBootTest
class SpringbootRedisApplicationTests {

    //该类中封装了很多api方法--redis服务
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //该类型其实是StringRedisTemplate的父类,
    @Resource
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
    }

    @Test
    public void test01() {
        //连接方式通过jar包直接连接
        //配置连接服务
        Jedis jedis = new Jedis("192.168.91.129", 6379);
        //输入设置的数据库密码
        jedis.auth("123456");

        //获取所有的key
        Set<String> keys = jedis.keys("*");
        keys.forEach(System.out::println);

        jedis.set("k1", "1");
        jedis.set("k2", "2");
        jedis.set("k3", "3");
        jedis.set("k4", "4");
        jedis.set("k5", "5");

        //删除指定的key
        Long c = jedis.del("k1", "k2", "k5");
        System.out.println("删除key的个数:" + c);

        //判断指定的key是否存在
        Boolean exists = jedis.exists("k2");
        System.out.println("判断key是否存在:" + exists);

        //关闭资源
        jedis.close();
    }

    @Test
    public void test02() {
        //连接方式通过jar包直接连接
        //配置连接服务
        Jedis jedis = new Jedis("192.168.91.129", 6379);
        //输入设置的数据库密码
        jedis.auth("123456");
        //存放字符串数据
        jedis.set("k1", "1");
        jedis.set("k2", "v2");

        //获取指定key的内容
        String value1 = jedis.get("k1");
        System.out.println("k1对应的内容:" + value1);

        //如果指定的key存在则不存入,不存在则存入redis
        Long aLong = jedis.setnx("k8", "ldh");
        System.out.println("是否存入:" + aLong);

        //存入时设置过期时间
        String str = jedis.setex("k5", 30l, "v5");
        System.out.println("存入的内容:" + str);

        //用于点赞和收藏
        Long incr = jedis.incr("k1");
        System.out.println("递增后的结果:" + incr);

        //关闭资源
        jedis.close();
    }

    @Test
    public void test03() {
        //对应hash类型的操作----可以存放对象。
        //连接方式通过jar包直接连接
        //配置连接服务
        Jedis jedis = new Jedis("192.168.91.129", 6379);
        //输入设置的数据库密码
        jedis.auth("123456");


        String name = jedis.hget("myhash", "name");
        System.out.println("获取hash中name对应的值:" + name);


        Map<String, String> map1 = jedis.hgetAll("myhash");
        System.out.println("获取指定key对应的内容:" + map1);

        Set<String> k11 = jedis.hkeys("myhash");
        System.out.println("获取myhash对应的所有field:" + k11);

        List<String> values = jedis.hvals("myhash");
        System.out.println("获取myhash对应的所有field的值:" + values);

        //关闭资源
        jedis.close();
    }

    @Test
    public void test04() {
        //为了减少频繁的创建和销毁jedis对象,提高了jedis的连接池,以提高连接效率。JedisPool

        //创建连接池的配置类
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMinIdle(5); //设置空闲的个数
        config.setMaxIdle(10);
        config.setMaxTotal(2000); //设置最多的数量
        config.setMaxWaitMillis(6000);//设置最大的等待时长
        config.setTestOnBorrow(true); //是否检验池子中的jedis对象可用
        //创建jedis连接池对象.格式 配置类 ip地址 端口号 超时时间 密码
        JedisPool jedisPool = new JedisPool(config, "192.168.91.129", 6379, 1000, "123456");

        //通过池子获取其中的一个连接 然后其他的操作和上面的一样
        Jedis jedis = jedisPool.getResource();

        Map<String, String> map1 = jedis.hgetAll("myhash");
        System.out.println("获取指定key对应的内容:" + map1);


    }

    //测试StringRedisTemplate
    @Test
    public void test06(){
    /*    //删除指定的key
        Boolean aBoolean = stringRedisTemplate.delete("k1");
        System.out.println("是否删除成功:"+aBoolean);

        //判断指定的key是否存在
        Boolean hasKey = stringRedisTemplate.hasKey("k1");
        System.out.println("判断指定的key是否存在:"+hasKey);
*/
        //获取对string类型操作的类对象
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        forValue.set("n1","测试数据1");
        forValue.set("n2","2");
        forValue.set("n3","测试数据3");

        //如果存在 则不存入 不存在则存入
        Boolean aBoolean = forValue.setIfAbsent("n4", "测试数据4", 25, TimeUnit.SECONDS);
        System.out.println("是否存入成功 " + aBoolean);


        //获取对应的值
        String n1 = forValue.get("n1");
        System.out.println("n1 = " + n1);

        //递增
        Long n2 = forValue.increment("n2");
        System.out.println("n2递增后的值" + n2);

    }



    @Test
    public void test07(){
        //对于hash类型的操作
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();


        //加入数据
        forHash.put("h1","name","刘德华");
        forHash.put("h1","age","18");
        forHash.put("h1","address","山东");

        HashMap<String,String> map = new HashMap<>();
        map.put("name","老六");
        map.put("age","19");
        map.put("adress","南京");
        forHash.putAll("h2",map);


        Object o = forHash.get("h1", "name");
        System.out.println("获取指定key对于的name的值:"+o);

        Map<Object, Object> h2 = forHash.entries("h2");
        System.out.println("获取h2对于的map对象:"+h2);

        Set<Object> keys = forHash.keys("h2");
        System.out.println("获取h2对于的所以field:"+keys);

        List<Object> values = forHash.values("h2");
        System.out.println("获取h2对于的所有filed的值:"+values);

    }


    // 而RedisTemplate的key和value可以自己指定数据类型,所有它的key和value可以是任意类型。
    @Test
    public void test08(){
        //默认RedisTemplate它的key和value的序列化都是使用的JdkSerializationRedisSerializer方式,
        // 该序列化要求类必须实现Serializable接口。
        //我们在实际开发中,我们的key都是String类型,我们应该指定String序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("student1",new Student(1,"张三","男"));
        System.out.println(valueOperations.get("student1"));
    }



}


Summarize

Guess you like

Origin blog.csdn.net/qq_55648724/article/details/128205051