美文网首页
java超快速入门(番外篇三)- java使用redis整理

java超快速入门(番外篇三)- java使用redis整理

作者: 自我De救赎 | 来源:发表于2021-10-02 23:30 被阅读0次

    关系图

    企业微信截图_32a52bc4-d930-4346-9b2b-2f3c2c6cfb66.png

    代码

    package com.sinbxeunha.josechan;
    
    import com.mysql.cj.jdbc.*;
    import com.sinbxeunha.josechan.entity.User;
    import io.lettuce.core.RedisClient;
    import io.lettuce.core.RedisURI;
    import io.lettuce.core.api.StatefulRedisConnection;
    import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
    import org.apache.ibatis.executor.result.DefaultResultHandler;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.mapping.Environment;
    import org.apache.ibatis.session.*;
    import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
    import org.junit.Test;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.cache.RedisCacheWriter;
    import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
    import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
    import org.springframework.data.redis.connection.lettuce.LettuceConnection;
    import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    
    import javax.naming.Reference;
    import javax.sql.DataSource;
    import javax.transaction.xa.XAResource;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.time.Duration;
    import java.util.*;
    
    //@SpringBootTest
    //@RunWith(SpringRunner.class)
    public class RedisTest {
    
        // 直接使用lettuce
        @Test
        public void lettuce() {
            // 配置客户端
            RedisClient redisClient = RedisClient.create(
                    RedisURI.builder()
    //                        .withPassword("123456789".toCharArray())
                            .withHost("127.0.0.1")
                            .withPort(6379)
                            .build()
            );
    
            //链接
            StatefulRedisConnection<String, String> connection = redisClient.connect();
    
            // 同步模式
            // 设置值
            connection.sync().set("hello", "world");
            // 异步模式
    //        connection.async().set("hello", "world");
    
            // 获取值
            String value = connection.sync().get("hello");
            System.out.println(value);
            // 删除值
            connection.sync().del("hello");
            // 断开连接
            connection.close();
        }
    
        // 使用LettuceConnection
        @Test
        public void lettuceConnection() {
            //配置项
            RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
            configuration.setHostName("127.0.0.1");
            configuration.setDatabase(0);
    //        configuration.setPassword("123456789");
    
            //工厂
            LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(configuration);
            // 该方法如果在spring中,将会在将对象注册成bean时调用
            // 因为这里手动new了对象,所以需要手动调用一下,以初始化工厂
            lettuceConnectionFactory.afterPropertiesSet();
            //获取链接
            LettuceConnection lettuceConnection = (LettuceConnection) lettuceConnectionFactory.getConnection();
            //请求
            lettuceConnection.stringCommands().set("hello".getBytes(), "world".getBytes());
            //断开
            lettuceConnection.close();
        }
    
        // 使用RedisTemplate
        @Test
        public void redisTemplate() {
            //配置项
            RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
            configuration.setHostName("127.0.0.1");
            configuration.setDatabase(0);
    //        configuration.setPassword("123456789");
            //工厂
            LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(configuration);
            lettuceConnectionFactory.afterPropertiesSet();
    
            RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
            //将工厂交给RedisTemplate,RedisTemplate将会根据工厂自动生产链接
            redisTemplate.setConnectionFactory(lettuceConnectionFactory);
            //同样需要手动调用一下以初始化RedisTemplate
            redisTemplate.afterPropertiesSet();
    
            // 使用execute方法
            redisTemplate.execute((connection) -> {
                return connection.stringCommands().set("hello1".getBytes(), "world1".getBytes());
            }, true);
        }
    
        //使用CacheManager
        @Test
        public void cacheManager(){
            //配置项
            RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
            configuration.setHostName("127.0.0.1");
            configuration.setDatabase(0);
    //        configuration.setPassword("123456789");
    
            RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
            HashMap<String, RedisCacheConfiguration> redisCacheConfigurations = new HashMap<String, RedisCacheConfiguration>();
            redisCacheConfigurations.put("default", redisCacheConfiguration);
            //工厂
            LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(configuration);
            lettuceConnectionFactory.afterPropertiesSet();
    
            RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(lettuceConnectionFactory);
            RedisCacheManager cacheManager = RedisCacheManager.RedisCacheManagerBuilder
                    .fromConnectionFactory(lettuceConnectionFactory)
                    .cacheWriter(cacheWriter)
                    .withInitialCacheConfigurations(redisCacheConfigurations)
                    .build();
            cacheManager.afterPropertiesSet();
            Objects.requireNonNull(cacheManager.getCache("default")).put("hello3", "world3");
        }
    }
    
    

    调用链

    redisTemplate

    1、@SpringBootApplication包含@EnableAutoConfiguration将会自动扫描AutoConfigure类,如RedisAutoConfiguration
    2、由于RedisAutoConfiguration被@Configuration注解,因此会自动注入RedisTemplate
    3、RedisAutoConfiguration类Import了LettuceConnectionConfiguration,LettuceConnectionConfiguration又被@Configuration注解了,因此会自动注入LettuceConnectionFactory,这样我们就能直接通过RedisTemplate使用LettuceConnection了

    CacheManager

    该类有如下注解@AutoConfigureAfter({RedisAutoConfiguration.class}),该注解使该类在RedisAutoConfiguration加载后加载,从而注入到容器中

    如果用户没有向容器注入org.springframework.data.redis.cache.RedisCacheConfiguration的实例,则会使用CacheProperties对象作为配置项

    相关文章

      网友评论

          本文标题:java超快速入门(番外篇三)- java使用redis整理

          本文链接:https://www.haomeiwen.com/subject/ugzmnltx.html