idea中使用Redis

jedis

  1. pom.xml文件引入依赖
  <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>3.2.0</version>
  </dependency>
  1. 导入后直接使用即可
        //创建jedis对象 这里的构造参数为host 和 port
        Jedis jedis = new Jedis("127.0.0.1",6379);
        //测试连接 如果连接成功会有返回值
        String value = jedis.ping();
        System.out.println(value);
  1. Jedis的一些操作
  • String
    //得到redis中所有key
    Set<String> keys = jedis.keys("*");
    //设置值
    jedis.set("k1","v1");
    //取值
    jedis.get("k1");
    //是否存在key
    jedis.exists("k1");
    //查看过期时间
    jedis.ttl("k1");
    //设置过期时间 2分钟
    jedis.expire("k1",120);
    //同时设置多个key,value
    jedis.mset("k1", "v1", "k2", "v2");
		//取多个值
		List<String> values = jedis.mget("k1", "k2");
  • List
	  //参数,key,start,stop  这里取全部
    jedis.lpush("myList","ele1");
    jedis.lpush("myList","ele2");
    jedis.lpush("myList","ele3");
    List<String> myList = jedis.lrange("myList", 0, -1);
    for (String ele : myList) {
      System.out.println(ele);
    }
  • set
        jedis.sadd("books","book01");
        jedis.sadd("books","book02");
        jedis.sadd("books","book03");
        Set<String> books = jedis.smembers("books");
        for (String book : books) {
            System.out.println(book);
        }
        //移除集合中一个或多个元素
        jedis.srem("books","book01","book02");
  • zSet
        jedis.zadd("games",100,"game01");
        jedis.zadd("games",80,"game02");
        jedis.zadd("games",90,"game03");
        jedis.zadd("games",70,"game04");

        Set<String> games = jedis.zrange("games", 0, -1);
        for (String game : games) {
            System.out.println(game);
        }
  • Hash
        jedis.hset("hash01","name","xiao");
        System.out.println(jedis.hget("hash01","name"));

        Map<String, String> hashMap = new HashMap<String, String>(10);
        hashMap.put("name","li");
        jedis.hset("hash02",hashMap);
        System.out.println(jedis.hget("hash02","name"));

springBoot整合redis

  1. pom文件引入依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
  1. application.properties配置redis
# Redis数据库索引(默认为0)  
spring.redis.database=0
# Redis服务器地址  
spring.redis.host=127.0.0.1
# Redis服务器连接端口  
spring.redis.port=6379
# Redis服务器连接密码(默认为空)  
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)  
spring.redis.pool.max-active=200
# 连接池最大阻塞等待时间(使用负值表示没有限制)  
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接  
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接  
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)  
spring.redis.timeout=1000
  1. 添加redis的配置类

用到redisTemplate

package com.example.springbootredis.conf;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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;

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        StringRedisSerializer redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashMap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        return template;
    }

}

  1. 编写Controller测试
package com.example.springbootredis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
@RequestMapping("/redisTest")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public void test(HttpServletResponse response){
        redisTemplate.delete("k1");
        //设置值
        redisTemplate.opsForValue().set("k1","v1");
        //获取值
        Object v1 = redisTemplate.opsForValue().get("k1");
        System.out.println(v1.toString());

        response.setContentType("json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.println(v1.toString());
        writer.close();

    }
}

注意事项

redis的配置文件(windows中) redis.windows.conf

  1. bind 默认绑定为本地的127.0.0.1 如果不去掉,将不能通过ip地址访问,需要注解掉

  1. 保护模式 protected-mode 默认为yes开启,不能远程访问,只能本地访问

改完配置文件后需要重启

如果在linux中,连接不上还可能是防火墙没关闭

看尚谷谷视频学习时的记录 https://www.bilibili.com/video/BV1Rv41177Af?p=21

推荐这些文章:

JAVA 编写测试类出现的问题(三)java.lang.NoClassDefFoundError: org/springframework/core/annotation/MergedAnnotations

java.lang.NoClassDefFoundError: org/springframework/core/annotation/MergedAnnotations
出现这个问题,找到此路径下的这个包发现都没有这个类。
实际上是我们引入的包的版本不对导致的。以上是我采用的pom包,当然有一些冗余,甄别自己的需要的去引用

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
&l...

文章标题:idea中使用Redis
文章链接:https://www.dianjilingqu.com/4408.html
本文章来源于网络,版权归原作者所有,如果本站文章侵犯了您的权益,请联系我们删除,联系邮箱:saisai#email.cn,感谢支持理解。
THE END
< <上一篇
下一篇>>