Redis(连接池)

SpringBoor环境下使用redis连接池

依赖:

<dependencies>
        <dependency>
            <groupId>com.yugabyte</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0-yb-11</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

测试类:“

package com.pb;

public class RedisTest1 {

    @Test
    public  void  test(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();   //创建连接池的配置对象
        jedisPoolConfig.setMaxTotal(100);    //并发量在100左右
        jedisPoolConfig.setMaxIdle(50);  //最大的等待连接
        jedisPoolConfig.setMinIdle(10);  //最小的等待连接
        jedisPoolConfig.setTestOnBorrow(false);   //其作用是设置在从连接池中获取连接时,是否检测并确保获取的连接可用。
        jedisPoolConfig.setTestOnReturn(false);   //用于设置在将连接还回连接池时是否检测连接的可用性
        jedisPoolConfig.setTestOnCreate(true);   //用于设置在创建新的连接时是否检测连接的可用性
        jedisPoolConfig.setBlockWhenExhausted(true);    //用于设置当连接池中的连接耗尽时,是阻塞等待还是立即抛出异常。

        jedisPoolConfig.setMaxWaitMillis(1000);  //等待1s

        //创建连接池
        JedisPool jedisPool=new JedisPool(jedisPoolConfig,"192.168.200.166",6380,2000,"123.com");

        Jedis jedis=null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(10);
            jedis.set("curry","库里");
            String curry = jedis.get("curry");
            System.out.println(curry);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis.close();  //关闭连接
        }

    }
}

Spring—Redis(连接池)

pom

<dependencies>
        <dependency>
            <groupId>com.yugabyte</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0-yb-11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.0.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
    </dependencies>

配置文件

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean  id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="100"/>
        <property name="maxIdle" value="50"/>
        <property name="minIdle" value="10"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>
        <property name="testOnCreate" value="false"/>
    </bean>

    <bean  id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:usePool="true" p:poolConfig-ref="jedisPoolConfig"
          p:hostName="192.168.200.166" p:port="6380" p:database="10"
          p:password="123.com" p:timeout="200000">
    </bean>

    <bean class="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="connectionFactory">

       
    </bean>

</beans>

测试:

package com.pb;


@RunWith(value = SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations ={"classpath:beans.xml"})
public class RedisTest1 {

    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public  void  test(){
        //System.out.println(redisTemplate);

        //操作Spring类型
        redisTemplate.opsForValue().set("aa","aa");

        String aa = (String) redisTemplate.opsForValue().get("aa");
        System.out.println(aa);

    }
}

但是出现了一个问题  就是乱码问题

需要在xml中  内部Bean

<bean class="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="connectionFactory">

        <!--创建一个内部Bean-->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>

        <!--创建一个内部Bean-->
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
    </bean>

但是这样子又出现一个问题 就是  保存对象的额时候出现的问题   可能还会出现乱码

/**
     * 存对象
     */
    @Test
    public void  test2(){

        User user = new User();
        user.setId(1);
        user.setName("curry");
        user.setSex("男");

        redisTemplate.opsForValue().set("user:1:info",user);

        User user1 = (User) redisTemplate.opsForValue().get("user:1:info");
        System.out.println(user1);

    }

上面的代码会报错  纯是编码问题:   

我们就需要在xml 中配置:

  <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
 </property>

 还有一个和就是可能会保存hash数据

  <!--创建一个内部Bean-->
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>

        <!--创建一个内部Bean-->
        <property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>

 测试:

 /**
     * 存hash
     */
    @Test
    public  void  test3(){
        Map<String, Object> map=new HashMap<>();
        User user = new User();
        user.setId(1);
        user.setName("curry");
        user.setSex("男");
        map.put("user11",user);
        redisTemplate.opsForHash().putAll("user:1:hash",map);


        User user11 = (User) redisTemplate.opsForHash().get("user:1:hash", "user11");

        System.out.println(user11);
    }
}

Spring—Boot声明式缓存

SpringBoot_data_redis

依赖:(boot版本   2.6.13)

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

配置文件  application.yml

spring:
  redis:
    host: 192.168.200.166
    port: 6380
    password: 123.com
    connect-timeout: 10000

    jedis:
      pool:
        max-active: 100
        max-idle: 50
        min-idle: 10
        max-wait: 1000
    database: 10

测试类:

package com.pb;


@SpringBootTest
class SpringBootDataRedisApplicationTests {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        System.out.println(redisTemplate);

        redisTemplate.opsForValue().set("java","opoo");
        String java = stringRedisTemplate.opsForValue().get("java");
        System.out.println(java);


        User user = new User(1001,"curry","男");

        redisTemplate.opsForValue().set("123123",user);
    }

}

不管是村对象还是存单个值 都有乱码问题  

我们需要写一个配置类

package com.pb.com.config;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory){

        RedisTemplate redisTemplate = new RedisTemplate();

        redisTemplate.setConnectionFactory(connectionFactory);

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

        redisTemplate.afterPropertiesSet();
        return  redisTemplate;
    }
}

在测试 就没有乱码了

过期时间:

@Test
    void  test(){
        redisTemplate.opsForValue().set("java","hello",5000, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("spring","spring", Duration.ofSeconds(5000));
    }

List集合:

 @Test
    void  test(){
        redisTemplate.opsForList().rightPushAll("user:1:info","11","22","33","44","55");

        List range = redisTemplate.opsForList().range("user:1:info", 0, -1);
        System.out.println(range);
    }

Hash

 @Test
    void  test2(){
        Map<String,Object> map=new HashMap<>();
        map.put("id",1001);
        map.put("name","詹姆斯");
        map.put("sex","男");

       redisTemplate.opsForHash().putAll("user:info",map);

       Map<Object,Object> entries=redisTemplate.opsForHash().entries("user:info");
       Iterator<Map.Entry<Object, Object>> integer=entries.entrySet().iterator();
       while (integer.hasNext()){
           Map.Entry<Object,Object>  next= integer.next();
           System.out.println(next.getKey()+"\t"+next.getValue());
       }

        Set<Object> keys = redisTemplate.opsForHash().keys("user:info");
        for (Object key : keys) {
            Object o = redisTemplate.opsForHash().get("user:info", key);
            System.out.println(o);

        }
    }

其他的操作   (匿名函数)

 @Test
    public  void test3(){
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushAll();
                return null;
            }
        });
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值