Table of Contents
1. Java connects to redis
1.1 Use Jedis
1.2 Use connection pool Connecting to redis
1.3 Java connecting to redis cluster mode
2. SpringBoot integrates redis
2.1 StringRedisTemplate
2.2 RedisTemplate
Home Java javaTutorial How Java and SpringBoot use redis

How Java and SpringBoot use redis

May 12, 2023 pm 08:31 PM
java redis springboot

1. Java connects to redis

What languages ​​does redis support and can be operated (check the redis official website)

How Java and SpringBoot use redis

How Java and SpringBoot use redis

1.1 Use Jedis

(1) Add jedis dependency

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <!--只能在测试类中使用-->
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.6.0</version>
        </dependency>

(2) Code test

public class TestJedis {
    @Test
    public void test01(){
        //连接redis--必须保证你的redis服务运行远程连接
        //该对象把每个redis命令封装成对应的方法
        //注意端口号
        //xshell中的redis要运行起来,注意防火墙释放端口号,注意配置文件的修改
        Jedis jedis=new Jedis("192.168.1.16",6379);
        //对于字符串操作的命令
        String set = jedis.set("k1", "v1");
        System.out.println(set);
        String set1 = jedis.set("k2", "v2");
        System.out.println(set1);
        String set2 = jedis.set("k3", "v3");
        System.out.println(set2);

        //对于hash的操作
        jedis.hset("k4","name","小花");
        Long hset = jedis.hset("k4", "age", "18");
        System.out.println(hset);

       Map<String ,String> map=new HashMap<>();
        map.put("name","小明");
        map.put("age","20");
        Long k = jedis.hset("k5", map);
        System.out.println(k);
        jedis.close();
    }
}

1.2 Use connection pool Connecting to redis

 @Test
    public void test02(){
        //创建连接池的配置类
        JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(20);
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setMaxWait(Duration.ofMillis(3000));
        JedisPool jedisPool=new JedisPool(jedisPoolConfig,"192.168.1.16",6379);
        long start = System.currentTimeMillis();

        for (int i = 0; i < 1000; i++) {
            //从jedis连接池获取资源
            Jedis jedis=jedisPool.getResource();
            String ping = jedis.ping();
            jedis.close();//是否关闭池子
        }
        long end=System.currentTimeMillis();
        //是为了比较使用池子还是不使用快,结论是使用池子快
        System.out.println("总耗时:"+(end-start));
    }

1.3 Java connecting to redis cluster mode

When connecting to the cluster, make sure there is no value stored in the cluster. If there is a value stored, you need to delete the previously generated file (make sure to delete it cleanly)

How Java and SpringBoot use redis

The other is to release the corresponding ports: 6001, 6002, 6003, 6004, 6005, 6006, because the port that was released before was actually 10000. Pay attention to the above two points before you can use the idea to create it successfully. .

@Test
    public void test03(){
      Set<HostAndPort> nodes=new HashSet<>();
      nodes.add(new HostAndPort("192.168.227.175",6001));
      nodes.add(new HostAndPort("192.168.227.175",6002));
      nodes.add(new HostAndPort("192.168.227.175",6003));
      nodes.add(new HostAndPort("192.168.227.175",6004));
      nodes.add(new HostAndPort("192.168.227.175",6005));
      nodes.add(new HostAndPort("192.168.227.175",6006));
        JedisCluster jedisCluster=new JedisCluster(nodes);
      jedisCluster.set("k6", "小老虎和小兔子");
        jedisCluster.close();
    }

How Java and SpringBoot use redis

2. SpringBoot integrates redis

springboot’s operation of redis encapsulates two StringRedisTemplate and RedisTemplate classes. StringRedisTemplate is a subclass of RedisTemplate, and StringRedisTemplate it Only string types can be stored, object types cannot be stored. If you want to use StringRedisTemplate to store objects, you must convert the object into a json string.

How Java and SpringBoot use redis

When springboot integrates redis, it provides two template tool classes, StringRedisTemplate and RedisTemplate.

2.1 StringRedisTemplate

(1) Introduce related dependencies

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

(2)Inject StringRedisTemplate object of this class

 @Autowired
 private StringRedisTemplate redisTemplate;

(3) Use StringRedisTemplate

This class seals the corresponding internal class separately for operations on each data type.

How Java and SpringBoot use redis

There will be no garbled characters here because the serialization and deserialization methods have been changed to String type.

@Autowired
    private StringRedisTemplate stringRedisTemplate;
 @Test
    public void test01(){
        //对hash类型的操作
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        forHash.put("k1","name","张三");
        forHash.put("k1","age","15");
        Map<String,String> map=new HashMap<>();
        map.put("name","李四");
        map.put("age","25");
        forHash.putAll("k36",map);
 
        Object o = forHash.get("k1", "name");
        System.out.println(o);
 
        Set<Object> k1 = forHash.keys("k1");
        System.out.println(k1);
 
        List<Object> k11 = forHash.values("k1");
        System.out.println(k11);
 
        //获取k1对于的所有的field和value
        Map<Object, Object> k12 = forHash.entries("k1");
        System.out.println(k12);
    }
    @Test
    void contextLoads() {
        //删除指定的key
       // stringRedisTemplate.delete("k");
        //查看所有的key
        //stringRedisTemplate.keys("k");
        //是否存在指定的key
        //stringRedisTemplate.hasKey("k");
        //对字符串数据类型的操作ValueOperations
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        //存储字符串类型--key value long uint  setex()
        forValue.set("k1","张三",30, TimeUnit.SECONDS);
        //等价于setnx 存入成功返回true ,失败返回false
        Boolean absent = forValue.setIfAbsent("k11", "李四", 30, TimeUnit.SECONDS);
        System.out.println(absent);
        //append拼接
        Integer append = forValue.append("k11", "真好看");
        String k11 = forValue.get("k11");
        System.out.println(k11);
 
    }

2.2 RedisTemplate

There will be garbled characters here because its serialization and deserialization methods default to JDK.

@SpringBootTest
class SbredisApplicationTests02 {
    //当你存储的value类型为对象类型使用redisTemplate
    //存储的value类型为字符串。StringRedisTemplate 验证码
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    public void test01(){
        //必须认为指定序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
 
        //对String类型操作类
        ValueOperations forValue = redisTemplate.opsForValue();
        //redis中key和value都变成了乱码
        //key和value都没有指定序列化方式,默认采用jdk的序列化方式
        forValue.set("k1","张三");
 
        //value默认采用jdk,类必须实现序列化接口
        forValue.set("k44",new User(1,"haha",12));
    }
}

The above RedisTemplate needs to specify the key value and field serialization method every time. Can you create a configuration class that has already specified serialization for RedisTemplate? No need to specify if used later.

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> 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序列化  filed value
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(redisSerializer);
        return template;
    }
}

The above is the detailed content of How Java and SpringBoot use redis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

You are not currently using a display attached to an NVIDIA GPU [Fixed] You are not currently using a display attached to an NVIDIA GPU [Fixed] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

How do you stay updated with the latest features and best practices for Redis? How do you stay updated with the latest features and best practices for Redis? Aug 20, 2025 pm 02:58 PM

Maintaining knowledge of Redis’s latest features and best practices is the key to continuous learning and focus on official and community resources. 1. Regularly check Redis official website, document updates and ReleaseNotes, subscribe to the GitHub repository or mailing list, get version update notifications and read the upgrade guide. 2. Participate in technical discussions on Redis's Google Groups mailing list, Reddit sub-section, StackOverflow and other platforms to understand other people's experience and problem solutions. 3. Build a local testing environment or use Docker to deploy different versions for functional testing, integrate the Redis upgrade test process in CI/CD, and master the value of feature through actual operations. 4. Close

Building Cloud-Native Java Applications with Micronaut Building Cloud-Native Java Applications with Micronaut Aug 20, 2025 am 01:53 AM

Micronautisidealforbuildingcloud-nativeJavaapplicationsduetoitslowmemoryfootprint,faststartuptimes,andcompile-timedependencyinjection,makingitsuperiortotraditionalframeworkslikeSpringBootformicroservices,containers,andserverlessenvironments.1.Microna

Java Persistence with Spring Data JPA and Hibernate Java Persistence with Spring Data JPA and Hibernate Aug 22, 2025 am 07:52 AM

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Fixed: Windows Is Showing 'A required privilege is not held by the client' Fixed: Windows Is Showing 'A required privilege is not held by the client' Aug 20, 2025 pm 12:02 PM

RuntheapplicationorcommandasAdministratorbyright-clickingandselecting"Runasadministrator"toensureelevatedprivilegesaregranted.2.CheckUserAccountControl(UAC)settingsbysearchingforUACintheStartmenuandsettingtheslidertothedefaultlevel(secondfr

See all articles