前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot系列之集成Jedis教程

SpringBoot系列之集成Jedis教程

作者头像
SmileNicky
修改2023-12-06 10:26:12
8260
修改2023-12-06 10:26:12
举报
文章被收录于专栏:Nicky's blog

SpringBoot系列之集成Jedis教程,Jedis是老牌的redis客户端框架,提供了比较齐全的redis使用命令,是一款开源的Java 客户端框架,本文使用Jedis3.1.0加上Springboot2.0,配合spring-boot-starter-data-redis使用,只给出简单的使用demo

软件环境:

  • JDK 1.8
  • SpringBoot 2.2.1
  • Maven 3.2+
  • Mysql 8.0.26
  • spring-boot-starter-data-redis 2.2.1
  • jedis3.1.0
  • 开发工具
    • IntelliJ IDEA
    • smartGit

项目搭建

使用Spring官网的https://start.spring.io快速创建Spring Initializr项目

选择maven、jdk版本

选择需要的Dependencies,选择一下Spring Data Redis

点击next就可以生成一个Springboot项目,不过jedis客户端配置还是要自己加的,所以对pom文件做简单的修改,spring-boot-starter-data-redis默认使用lettuce,所以不用的可以exclusion,然后再加上jedis的配置

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

新建一个application.yml配置文件,加上redis一些配置

代码语言:javascript
复制
spring:
  redis:
    port: 6379
    host: 127.0.0.1
    password:
    timeout: 3000
    database: 1
    jedis:
      pool:
        max-idle: 8
        max-active: 8
        min-idle: 2

新增Redis配置,配置RedisConnectionFactory JedisConnectionFactoryJedisPoolRedisTemplate需要用到也可以配置一下

代码语言:javascript
复制
package com.example.jedis.configuration;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
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;

@Configuration
@ConditionalOnClass({GenericObjectPool.class, JedisConnection.class, Jedis.class})
@EnableRedisRepositories(basePackages = "com.example.jedis.repository")
@Slf4j
public class RedisConfiguration {

    @Value("${spring.redis.host:127.0.0.1}")
    private String host;
    @Value("${spring.redis.port:6379}")
    private Integer port;
    @Value("${spring.redis.password:}")
    private String password;
    @Value("${spring.redis.database:0}")
    private Integer database;

    @Value("${spring.redis.jedis.pool.max-active:8}")
    private Integer maxActive;
    @Value("${spring.redis.jedis.pool.max-idle:8}")
    private Integer maxIdle;
    @Value("${spring.redis.jedis.pool.max-wait:-1}")
    private Long maxWait;
    @Value("${spring.redis.jedis.pool.min-idle:0}")
    private Integer minIdle;


    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWait);
        jedisPoolConfig.setMaxTotal(maxActive);
        jedisPoolConfig.setMinIdle(minIdle);
        return jedisPoolConfig;
    }

    @Bean
    public RedisStandaloneConfiguration jedisConfig() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);
        config.setPort(port);
        config.setDatabase(database);
        config.setPassword(RedisPassword.of(password));
        return config;
    }


    @Bean
    public JedisPool jedisPool() {
      return new JedisPool(jedisPoolConfig());
    }


    @Bean
    public RedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisConfig());
        jedisConnectionFactory.setPoolConfig(jedisPoolConfig());
        return jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }





}

写一个实体类,@RedisHash定义存储的hash key

代码语言:javascript
复制
package com.example.jedis.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.springframework.data.redis.core.RedisHash;

import java.io.Serializable;

@RedisHash("user")
@Data
@SuperBuilder(toBuilder = true)
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
public class UserDto implements Serializable {


    private static final long serialVersionUID = 5962011647926411830L;

    public enum Gender {
        MALE, FEMALE
    }

    private Long id;
    private String name;
    private Gender gender;

}

使用Sping Data Redis的API来实现一个CRUD接口

代码语言:javascript
复制
package com.example.jedis.repository;


import com.example.jedis.model.UserDto;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<UserDto, Long> {
}

写一个测试类来进行测试,ContextConfiguration指定一个配置类

代码语言:javascript
复制
package com.example.jedis;

import cn.hutool.core.util.IdUtil;
import com.example.jedis.configuration.RedisConfiguration;
import com.example.jedis.model.UserDto;
import com.example.jedis.repository.UserRepository;
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.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@SpringBootTest
@ContextConfiguration(classes = RedisConfiguration.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
class SpringbootJedisApplicationTests {

    @Autowired
    JedisPool jedisPool;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserRepository userRepository;

    @Test
    void contextLoads() {
        Jedis jedis= jedisPool.getResource();
        jedis.set("tKey","你好呀");
        jedis.close();

    }

    @Test
    void testRedisTemplate() {
        redisTemplate.opsForValue().set("rtKey","你好呀");
    }

    @Test
    void testCrud() {
        final UserDto userDto = UserDto.builder()
                .id(IdUtil.getSnowflake().nextId())
                .name("用户1")
                .gender(UserDto.Gender.MALE)
                .build();
        userRepository.save(userDto);
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-12-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 软件环境:
  • 项目搭建
相关产品与服务
云数据库 Redis®
腾讯云数据库 Redis®(TencentDB for Redis®)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档