redis spring怎么整合

Posted

tags:

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

参考技术A redis与Spring集成比较简单,本文不涉及Spring的一些基本概念,读都需先具备Spring的相关知识。
先在maven中添加依赖
pom.xml
<!-- redis -->
<dependency>
‍ <groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.0.0</version>
</dependency> ‍
<!-- redis -->

applicationContext-redis.xml加入你的Spring context
<?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:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxActive" value="50" /> <!--最大连接数-->
<property name="maxIdle" value="10" /> <!--最大空闲数-->
<property name="maxWait" value="1000" /> <!--最大等待时间ms-->
<property name="testOnBorrow" value="true" />
</bean>
<bean id="jedis.shardInfo" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="172.21.1.121" />
<constructor-arg index="1" value="6379" />
</bean>
<bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"> <constructor-arg index="0" ref="jedisPoolConfig" />
<constructor-arg index="1">
<list>
<ref bean="jedis.shardInfo" />
</list>
</constructor-arg>
</bean>
</beans>

RedisDao.java操作redis的类
/**
*
*/package com.zolcorp.mahout.dao;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
/**
* @author hadoop
*
*/
public class RedisDao
@Autowired
private ShardedJedisPool shardedJedisPool;
public void set(String key, String value)
ShardedJedis jedis = shardedJedisPool.getResource();
jedis.set(key, value);

public String get(String key)
ShardedJedis jedis = shardedJedisPool.getResource();
return jedis.get(key);



其它一些方法,请读者自己完成。
<bean id="redisDao" class="com.zolcorp.mahout.dao.RedisDao"></bean>

注册bean
main函数如下:
/**
*
*/
package com.zolcorp.mahout.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContex; import com.zolcorp.mahout.dao.RedisDao;
/**
* @author hadoop
*
*/
public class RedisMain
/**
* @param args
*/
public static void main(String[] args)
ApplicationContext context = new FileSystemXmlApplicationContext( new String[] "classpath:applicationContext-bean.xml",
"classpath:applicationContext-datasource.xml",
"classpath:applicationContext-redis.xml");
RedisDao redisDao = context.getBean("redisDao", RedisDao.class);
redisDao.set("test", "test-----ming...");
System.out.println(redisDao.get("test")); //test-----ming...

本回答被提问者和网友采纳

jedis的使用,spring整合redis,springboot整合redis

  1. java使用redis

很简单,看我的github的例子就行

  1. spirng整合redis,这里用xml配置方式实现

2.1导包

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-redis</artifactId>
  <version>1.0.2.RELEASE</version>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.1.0</version>
</dependency>

2.2配置applicationContext.xml

Spring提供了很多序列化器

Jackson2JsonRedisSerializer

JdkSerializationRedisSerializer

OxmSerializer

StringRedisSerializer

GenericToStringRedisSerializer

GenericJackson2JsonRedisSerializer

 

<!--redisconfig-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxIdle" value="50" />
    <property name="maxActive" value="100" />
    <property name="maxWait" value="6000"/>
</bean>
<!--rdis连接工厂-->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="localhost" />
    <property name="port" value="6379" />
    <property name="poolConfig" ref="poolConfig" />
</bean>

<!--string jdk序列化器-->
<bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />

<!--配置redisTemplate-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <!--keyvalue的序列化方式常用string或者jdk-->
   
<property name="keySerializer" ref="stringRedisSerializer" />
    <property name="valueSerializer" ref="stringRedisSerializer" />
</bean>

2.3测试

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
RedisTemplate redisTemplate = applicationContext
        .getBean(RedisTemplate.class);

2.4   StringRedisTemplete和RedisTemplete的区别

StringRedisTemplete继承RedisTemplete,内部使用string序列化器,所以适合操作key和value都是string的数据

 

3 Spring中发布订阅

3.1首先提供接收消息的类,它将实现 org.springframework.data.redis.connection.MessageListener 接口,并实现接口定义的方法 public void onMessage(Message message,byte[]pattern)

/*** imports ***/

  1. public class RedisMessageListener implements MessageListener {
  2.     private RedisTemplate redisTemplate;
  3.  
  4.     /*** 此处省略redisTemplate的 setter和getter方法 ***/
  5.     @Override
  6.     public void onMessage(Message message, byte[] bytes) {
  7.         // 获取消息
  8.         byte[] body = message.getBody();
  9.         // 使用值序列化器转换
  10. 10.         String msgBody = (String) getRedisTemplate().getValueSerializer()
  11. 11.                 .deserialize(body);
  12. 12.         System.err.println(msgBody);
  13. 13.         // 获取 channel
  14. 14.         byte[] channel = message.getChannel();
  15. 15.         // 使用字符串序列化器转换
  16. 16.         String channelStr = (String) getRedisTemplate().getStringSerializer()
  17. 17.                 .deserialize(channel);
  18. 18.         System.err.println(channelStr);
  19. 19.         // 渠道名称转换
  20. 20.         String bytesStr = new String(bytes);
  21. 21.         System.err.println(bytesStr);
  22. 22.     }

23. }

3.2.在spring中配置自定义的监听器

<!--配置redis监听器-->
<bean id="messageListener" class="com.zy.listener.RedisMessageListener">
    <property name="stringRedisSerializer" ref="stringRedisSerializer"/>
    <property name="jdkSerializationRedisSerializer" ref="jdkSerializationRedisSerializer"/>
</bean>
3.3 要给一个监听容器,在 Spring 中已有类 org.springframework.data.redis.listener.RedisMessageListenerContainer。它可以用于监听 Redis 的发布订阅消息,下面的配置就是为了实现这个功能,读者可以通过注释来了解它的配置要点。

<!--配置redis监听器container-->
<!--
配置线程池-->
<bean id="poolTaskScheduler"
        class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
    <property name="poolSize" value="3" />
</bean>
<!--配置容器,topic是监听的通道的名称,自定义的-->
<redis:listener-container connection-factory="connectionFactory" task-executor="poolTaskScheduler" topic-serializer="stringRedisSerializer">
    <redis:listener ref="messageListener" method="onMessage" topic="chat" serializer="stringRedisSerializer"/>
</redis:listener-container>

3.4 测试,像chat通道发送消息

  1. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  2. RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
  3. String channel = "chat";
  4. redisTemplate.convertAndSend(channel, "I am lazy!!");

4 springboot整合redis

4.1新建springboot项目,勾选上redis

 4.2配置application.yml

        spring:
  redis:
    host: 127.0.0.1
    port: 6379
    jedis:
      pool:
        max-active: 100
        max-idle: 10
        max-wait: 20000
    lettuce:
      shutdown-timeout: 1000

4.2 配置redis的配置类

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(stringRedisSerializer());
        redisTemplate.setValueSerializer(jdkSerializationRedisSerializer());
        return redisTemplate;
    }
   
    @Bean
    public StringRedisSerializer stringRedisSerializer(){
        return new StringRedisSerializer();
    }
    @Bean
    public JdkSerializationRedisSerializer jdkSerializationRedisSerializer(){
        return new JdkSerializationRedisSerializer();
    }
}

4.3 测试

@SpringBootTest
class SpringbootRedisApplicationTests {
@Autowired
private RedisTemplate<String,Object> redisTemplate;
    @Test
    void contextLoads() {
        redisTemplate.opsForValue().set("myname","zhouyang");
        String myname = (String)redisTemplate.opsForValue().get("myname");
        System.out.println(myname);
    }

}

4.4 配置订阅发布

 4.4.1新建类实现MessageListener

        public class MyRedisMessageListener implements MessageListener {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void onMessage(Message message, byte[] bytes) {
        // 获取消息
              
byte[] body = message.getBody();
               // 使用值序列化器转换
                  
String msgBody = (String) redisTemplate.getValueSerializer()
                           .deserialize(body);
                System.err.println(msgBody);
                   // 获取 channel
                  
byte[] channel = message.getChannel();
                   // 使用字符串序列化器转换
              
String channelStr = (String) redisTemplate.getStringSerializer()
                           .deserialize(channel);
                System.err.println(channelStr);
                // 渠道名称转换
              
String bytesStr = new String(bytes);
               System.err.println(bytesStr);

    }
}

4.4.2 配置redisConfig,把messageListener和containner放入容器中

@Bean
public MyRedisMessageListener myRedisMessageListener(){
    return new MyRedisMessageListener();
}
@Bean
public RedisMessageListenerContainer  redisMessageListenerContainer (RedisConnectionFactory redisConnectionFactory){
    RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
    redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
    redisMessageListenerContainer.addMessageListener(myRedisMessageListener(),new PatternTopic("chat"));
    return redisMessageListenerContainer;
}

4.4.3测试

@Test
void testPublish() {
    redisTemplate.convertAndSend("chat","我是周扬");
}

 

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

spring整合jedis怎么指定密码

mybaits和spring整合后pojo扫描怎么配置

Spring优雅整合Redis缓存

redis和mysql怎么一起在springmvc里面

Spring Boot如何整合Redis

Spring Boot如何整合Redis