springboot整合redis

一、总体概述

1、redis配置文件

springboot整合redis_第1张图片

redis.conf配置文件,改完后确保生效,记得重启,记得重启

  • 默认daemonize no 改为 daemonize yes

  • 默认protected-mode yes 改为 protected-mode no

  • 默认bind 127.0.0.1 改为 直接注释掉(默认bind 127.0.0.1只能本机访问)或改成本机IP地址,否则影响远程IP连接

  • 添加redis密码 改为 requirepass 你自己设置的密码

2、设置防火墙

启动: systemctl start firewalld
关闭: systemctl stop firewalld
查看状态: systemctl status firewalld 
开机禁用  : systemctl disable firewalld
开机启用  : systemctl enable firewalld    
添加 :firewall-cmd --zone=public --add-port=80/tcp --permanent    (--permanent永久生效,没有此参数重启后失效)
重新载入: firewall-cmd --reload
查看: firewall-cmd --zone= public --query-port=80/tcp
删除: firewall-cmd --zone= public --remove-port=80/tcp --permanent

3、jedis(一般不用,了解即可)

public class JedisDemo
{
    public static void main(String[] args)
    {
        //1 connection获得,通过指定ip和端口号
        Jedis jedis = new Jedis("192.168.159.130", 6379);
        //2 指定访问服务器的密码
        jedis.auth("yjy219912ym");
        //3 获得了jedis客户端,可以像jdbc一样,访问我们的redis
        System.out.println(jedis.ping());

        //keys
        Set<String> keys = jedis.keys("*");
        System.out.println(keys);

        //string
        jedis.set("k3","hello-jedis");
        System.out.println(jedis.get("k3"));
        System.out.println(jedis.ttl("k3"));
        jedis.expire("k3",20L);

        //list
        jedis.lpush("list","11","12","13");
        List<String> list = jedis.lrange("list", 0, -1);
        for (String element : list) {
            System.out.println(element);
        }
        // hash
        jedis.hset("hset1","k1","v1");
        Map<String,String> hash = new HashMap<>();
        hash.put("k1","1");
        hash.put("k2","2");
        hash.put("k3","3");
        jedis.hmset("hset2",hash);
        System.out.println(jedis.hmget("hset2","k1","k3","k2"));
        System.out.println(jedis.hget("hset1", "k1"));
        System.out.println(jedis.hexists("hset2","k2"));
        System.out.println(jedis.hkeys("hset2"));

        // set
        jedis.sadd("set1","1","2","3");
        jedis.sadd("set2","4");
        System.out.println(jedis.smembers("set1"));
        System.out.println(jedis.scard("set1"));
        System.out.println(jedis.spop("set1"));
        jedis.smove("set1","set2","1");
        System.out.println(jedis.smembers("set1"));
        System.out.println(jedis.smembers("set2"));
        System.out.println(jedis.sinter("set1", "set2"));  // 交集
        System.out.println(jedis.sunion("set1","set2"));   // 并集

        // zset
        jedis.zadd("zset1",100,"v1");
        jedis.zadd("zset1",80,"v2");
        jedis.zadd("zset1",60,"v3");

        List<String> zset1 = jedis.zrange("zset1", 0, -1);
        for (String s : zset1) {
            System.out.println(s);
        }
        List<String> zset11 = jedis.zrevrange("zset1", 0, -1);
        for (String s : zset11) {
            System.out.println(s);
        }
    }
}

4、lettuce(了解)

springboot整合redis_第2张图片


```dart
public class LettuceDemo
{
    public static void main(String[] args)
    {
        // 1 使用构建器链式编程来builder我们RedisURI
        RedisURI uri = RedisURI.builder()
                .redis("192.168.159.130")
                .withPort(6379)
                .withAuthentication("default","yjy219912ym")
                .build();

        //2 创建连接客户端
        RedisClient redisClient = RedisClient.create(uri);
        StatefulRedisConnection conn = redisClient.connect();

        //3 通过conn创建操作的command
        RedisCommands commands = conn.sync();

        //========biz====================
        //keys
        List keys = commands.keys("*");
        System.out.println("***********"+keys);

        //string
        commands.set("k5","hello-lettuce");
        System.out.println("***********"+commands.get("k5"));

        // list
        commands.lpush("list01","1","2","3");
        List<String> list01 = commands.lrange("list01", 0, -1);
        for (String s : list01) {
            System.out.println("================"+s);
        }
        System.out.println("===================="+ commands.rpop("list01", 2));

        // hash
        commands.hset("hash","k1","v1");
        commands.hset("hash","k2","v2");
        commands.hset("hash","k3","v3");
        System.out.println("======================="+commands.hgetall("hash"));
        Boolean hexists = commands.hexists("hash", "v2");
        System.out.println("------"+hexists);

        // set
        commands.sadd("s1","1","2");
        System.out.println("=================================" + commands.smembers("s1"));
        System.out.println(commands.sismember("s1", "1"));
        System.out.println(commands.scard("s1"));

        // zset
        commands.zadd("a1",100,"v1");
        commands.zadd("a1",80,"v2");
        System.out.println(commands.zrange("a1", 0, -1));
        System.out.println("======================"+commands.zcount("a1", "90", "100"));

        //4 各种关闭释放资源
        conn.close();
        redisClient.shutdown();
    }
}

5、RedisTemplate(推荐使用)

配置

spring.redis.database=0
spring.redis.host=192.168.159.130
spring.redis.port=6379
spring.redis.password=yjy219912ym
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0

service



public class OrderService
{

    public static final String ORDER_KEY = "ord:";

     private RedisTemplate redisTemplate;
    //@Resource private StringRedisTemplate StringRedisTemplate;

    public void addOrder()
    {
        int keyId = ThreadLocalRandom.current().nextInt(1000)+1;
        String serialNo = UUID.randomUUID().toString();

        String key = ORDER_KEY+keyId;
        String value = "京东订单"+serialNo;

        redisTemplate.opsForValue().set(key,value);


        log.info("***key:{}",key);
        log.info("***value:{}",value);
    }

    public String getOrderById(Integer keyId)
    {
        return (String) redisTemplate.opsForValue().get(ORDER_KEY + keyId);
        //return StringRedisTemplate.opsForValue().get(ORDER_KEY + keyId);
    }

}

controller



(tags = "订单接口")
public class OrderController
{
    
    private OrderService orderService;

    ("新增订单")
    (value = "/order/add",method = RequestMethod.POST)
    public void addOrder()
    {
        orderService.addOrder();
    }

    ("按照keyIdc查询订单")
    (value = "/order/{keyId}",method = RequestMethod.GET)
    public String getOrderById( Integer keyId)
    {
        return orderService.getOrderById(keyId);
    }
}

序列化问题
springboot整合redis_第3张图片
方法一:用StringRedisTemplate,redis客户端查看value的时候加上–raw
方法二:写redisconfig


public class RedisConfig
{
    /**
     * redis序列化的工具配置类,下面这个请一定开启配置
     * 127.0.0.1:6379> keys *
     * 1) "ord:102"  序列化过
     * 2) "\xac\xed\x00\x05t\x00\aord:102"   野生,没有序列化过
     * this.redisTemplate.opsForValue(); //提供了操作string类型的所有方法
     * this.redisTemplate.opsForList(); // 提供了操作list类型的所有方法
     * this.redisTemplate.opsForSet(); //提供了操作set的所有方法
     * this.redisTemplate.opsForHash(); //提供了操作hash表的所有方法
     * this.redisTemplate.opsForZSet(); //提供了操作zset的所有方法
     * @param lettuceConnectionFactory
     * @return
     */
    
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory)
    {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        //设置key序列化方式string
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置value的序列化方式json,使用GenericJackson2JsonRedisSerializer替换默认序列化
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }
}

6、集群

配置

spring.redis.password=111111
spring.redis.cluster.max-redirects=3
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.cluster.refresh.adaptive=true
spring.redis.lettuce.cluster.refresh.period=2000
spring.redis.cluster.nodes=192.168.111.185:6381,192.168.111.185:6382,192.168.111.172:6383,192.168.111.172:6384,192.168.111.184:6385,192.168.111.184:6386

springboot整合redis_第4张图片
问题:要是有一台主机比如6381宕机了,redis那边工作还是正常,但是java这边的工作出现了问题
springboot整合redis_第5张图片
springboot整合redis_第6张图片
springboot整合redis_第7张图片
原因:
springboot整合redis_第8张图片

你可能感兴趣的:(redis,redis,spring,boot,java)