springboot整合jedis

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合jedis相关的知识,希望对你有一定的参考价值。

参考技术A

jedis来实现redis缓存,Jedis2.7以上的版本才支持集群操作

redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to host ***.***.*.**
解决:因为docker 的redis默认启动,自带的配置文件redis.conf文件里有bind 127.0.0.1(只能本地链接,拒绝外部链接), 注释bind 127.0.0.1 即可,再用数据卷映射容器内的redis.conf文件的方式启动redis

springboot整合redis

在springboot1.x系列中,其中连接redis服务器使用的是jedis,但是到了springboot2.x使用的是Lettuce。
关于jedis跟lettuce的区别:

  • Lettuce 和 Jedis 的定位都是Redis的client,所以他们当然可以直接连接redis server。
  • Jedis在实现上是直接连接的redis server,如果在多线程环境下是非线程安全的,这个时候只有使用连接池,为每个Jedis实例增加物理连接
  • Lettuce的连接是基于Netty的,连接实例(StatefulRedisConnection)可以在多个线程间并发访问,应为StatefulRedisConnection是线程安全的,所以一个连接实例(StatefulRedisConnection)就可以满足多线程环境下的并发访问,当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。

新建一个springboot工程
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-boot-redis</artifactId>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- redis依赖commons-pool 这个依赖一定要添加 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

    </dependencies>

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

yml 文件

server:
  port: 8080
spring:
  redis:
    cluster:
      nodes: 192.168.159.129:7001,192.168.159.129:7002,192.168.159.129:7003,192.168.159.129:7004,192.168.159.129:7005,192.168.159.129:7006
    host: localhost
    port: 6379
    lettuce:
      pool:
        #连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal
        maxActive: 600
        #最大空闲数
        maxIdle: 200
        minIdle: 0
        #控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
        maxTotal: 1000
        #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
        maxWaitMillis: 5000
    password:

redisConfig类

package com.sl.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author shuliangzhao
 * @Title: RedisConfiguration
 * @ProjectName design-parent
 * @Description: TODO
 * @date 2019/7/13 16:55
 */
@Configuration
public class RedisConfiguration 
    @Value("$spring.redis.cluster.nodes")
    private String nodes;
    @Value("$spring.redis.host")
    private String host;
    @Value("$spring.redis.port")
    private Integer port;
    @Value("$spring.redis.password")
    private String password;
    @Value("$spring.redis.lettuce.pool.maxIdle:")
    private Integer maxIdle;
    @Value("$spring.redis.lettuce.pool.minIdle:")
    private Integer minIdle;
    @Value("$spring.redis.lettuce.pool.maxTotal:")
    private Integer maxTotal;
    @Value("$spring.redis.lettuce.pool.maxWaitMillis:")
    private Long maxWaitMillis;
    @Value("$spring.redis.lettuce.pool.maxActive:")
    private Long maxActive;

    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory() 
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        LettucePoolingClientConfiguration lettucePoolingClientConfiguration = LettucePoolingClientConfiguration.builder()
                .poolConfig(poolConfig)
                .build();
        //单机redis
        RedisStandaloneConfiguration redisConfig  = new RedisStandaloneConfiguration();
        redisConfig.setHostName(StringUtils.isBlank(host) ? "localhost":host.split(":")[0]);
        redisConfig.setPort(port != null ? 6379: Integer.valueOf(host.split(":")[1]));
        redisConfig.setPassword(StringUtils.isNotBlank(password) ? password : "");
        // 集群redis
        /*RedisClusterConfiguration redisConfig = new RedisClusterConfiguration();
        Set<RedisNode> nodeses = new HashSet<>();*/
        return new LettuceConnectionFactory(redisConfig, lettucePoolingClientConfiguration);
    

    @Bean
    public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) 
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(om);
        //redisTemplate.setDefaultSerializer(genericJackson2JsonRedisSerializer);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
        return redisTemplate;
    

User实体类

package com.sl.entity;

/**
 * @author shuliangzhao
 * @Title: User
 * @ProjectName design-parent
 * @Description: TODO
 * @date 2019/7/13 17:41
 */
public class User 

    private String name;

    private String age;

    private String job;

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public String getAge() 
        return age;
    

    public void setAge(String age) 
        this.age = age;
    

    public String getJob() 
        return job;
    

    public void setJob(String job) 
        this.job = job;
    

controller

package com.sl.controller;

import com.alibaba.fastjson.JSONObject;
import com.sl.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author shuliangzhao
 * @Title: RedisController
 * @ProjectName design-parent
 * @Description: TODO
 * @date 2019/7/13 17:40
 */
@RestController
public class RedisController 

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("/user/save")
    public void saveUser() 
        User user = new User();
        user.setName("张三");
        user.setAge("18");
        user.setJob("程序员");
        redisTemplate.opsForValue().set("userZhang", JSONObject.toJSONString(user));
    

    @RequestMapping("/user/get")
    public String getUser() 
        return (String)redisTemplate.opsForValue().get("userZhang");
    

启动类

package com.sl;

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

@SpringBootApplication
public class SpringBootRedisApplication 

    public static void main(String[] args) 
        SpringApplication.run(SpringBootRedisApplication.class, args);
    


spring-data-redis的序列化类有下面这几个:
1.GenericToStringSerializer: 可以将任何对象泛化为字符串并序列化
2.Jackson2JsonRedisSerializer: 跟JacksonJsonRedisSerializer实际上是一样的
3.JacksonJsonRedisSerializer: 序列化object对象为json字符串
4.JdkSerializationRedisSerializer: 序列化java对象(被序列化的对象必须实现Serializable接口)
5.StringRedisSerializer: 简单的字符串序列化
6.GenericToStringSerializer:类似StringRedisSerializer的字符串序列化
7.GenericJackson2JsonRedisSerializer:类似Jackson2JsonRedisSerializer,但使用时构造函数不用特定的类参考以上序列化,自定义序列化类;

StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存,StringRedisSerializer。
RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。JdkSerializationRedisSerializer
key和hashKey: 推荐使用 StringRedisSerializer: 简单的字符串序列化
hashValue: 推荐使用 GenericJackson2JsonRedisSerializer:类似Jackson2JsonRedisSerializer,但使用时构造函数不用特定的类。
源码在github上面 地址为:https://github.com/FadeHub/spring-boot-learn

以上是关于springboot整合jedis的主要内容,如果未能解决你的问题,请参考以下文章

[SpringBoot系列]SpringBoot如何整合SSMP

springboot怎么整合activiti

SpringBoot完成SSM整合之SpringBoot整合junit

springboot整合jedis

SpringBoot 整合其他框架 -- SpringBoot整合Mybatis

SpringBoot 整合其他框架 -- SpringBoot整合Junit