Java Spring Redis搭建

Redis安装

首先,要去官网安装相应平台的redis,这部分比较简单直接查询即可。

流程概述

Spring Redis使用基本功能比较简单,通过Spring的依赖注入功能,实现Redis所需要的redis连接池配置类JedisPoolConfig、redis连接工厂实现类JedisConnectionFactory、和redis访问功能封装类RedisTemplate,并提供相应的DAO类对RedisTemplate封装,就可以使用。简单来说,就是配置redis连接信息,然后利用连接信息生成连接池,然后在RedisTemplate中对连接池进行操作,最后我们进行一层封装更方便实现业务逻辑。
而在实现发布订阅功能时,还要实现相应的监听器。再通过注入RedisMessageListenerContainer,把我们实现的监听器进行注册。

配置Spring Redis

首先在pom中添加依赖包:

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${redis.client.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>${redis.data.version}</version>
        </dependency>

在web.xml中加载spring相关配置的时候,建议使用如下形式:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>

这样会自动去加载装配所需要的全部bean,可以将spring、redis、mybatis等需要的bean分开来。Spring的配置略过,查看Spring redis的配置:

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
       default-lazy-init="true">

    <context:component-scan base-package="com.mk.util.redis"/>
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>

    <!-- 连接池配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!-- 连接池中最大空闲的连接数 -->
        <property name="maxIdle" value="${jedis.maxIdle}"></property>
        <!-- 连接空闲的最小时间,达到此值后空闲连接将可能会被移除。负值(-1)表示不移除. -->
        <property name="minEvictableIdleTimeMillis" value="${jedis.minEvictableIdleTimeMillis}"></property>
        <!-- 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3 -->
        <property name="numTestsPerEvictionRun" value="${jedis.numTestsPerEvictionRun}"></property>
        <!-- “空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1. -->
        <property name="timeBetweenEvictionRunsMillis" value="${jedis.timeBetweenEvictionRunsMillis}"></property>
    </bean>

    <!-- Spring提供的Redis连接工厂 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
        <!-- 连接池配置 -->
        <property name="poolConfig" ref="jedisPoolConfig"></property>
        <!-- Redis服务主机 -->
        <property name="hostName" value="${redis.hostName}"></property>
        <!-- Redis服务端口号 -->
        <property name="port" value="${redis.port}"></property>
        <!-- 连超时设置 -->
        <property name="timeout" value="${redis.timeout}"></property>
        <!-- 是否使用连接池 -->
        <property name="usePool" value="${redis.usePool}"></property>
        <!-- Redis服务连接密码 -->
        <!--<property name="password" value="${redis.password}"></property>-->
    </bean>

    <!-- Spring提供的访问Redis类 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <!-- Redis连接工厂 -->
        <property name="connectionFactory" ref="jedisConnectionFactory"></property>
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <!-- JdkSerializationRedisSerializer支持对所有实现了Serializable的类进行序列化 -->
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
        </property>
    </bean>


    <!--下面是自己编写的监听器,用来实现发布订阅功能的,对于基础的redis使用不需要-->
    <bean id="redisMessageListener" class="com.mk.util.redis.listener.RedisMessageListener"/>
    <bean  class="org.springframework.data.redis.listener.RedisMessageListenerContainer"
          destroy-method="destroy">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
        <property name="taskExecutor">
            <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
                <property name="corePoolSize" value="5"/>
            </bean>
        </property>
        <property name="messageListeners">
            <map>
                <entry key-ref="redisMessageListener">
                    <!--这里配置频道信息-->
                    <bean class="org.springframework.data.redis.listener.ChannelTopic">
                        <constructor-arg value="audit"/>
                    </bean>
                </entry>
            </map>

        </property>
    </bean>
</beans>

因为这里除了基本的数据存储查询,同样实现了Redis的发布订阅功能,如果不需要的话,那么后半段配置可以去掉。

然后是封装增删改查订阅的功能类:

package com.mk.util.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * Created by yangyangos3098 on 2017/1/20.
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public void set(String key, Object val) {
        redisTemplate.boundValueOps(key).set(val);
    }

    public Object get(String key) {
        return redisTemplate.boundValueOps(key).get();
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 发布消息
     * @param channel 发布的频道,需要在redis配置文件中进行配置
     * @param message
     */
    public void sendMessage(String channel, Serializable message) {
        redisTemplate.convertAndSend(channel,message);
    }
}

之后是发布订阅过程中,传递的消息bean类型:

package com.mk.util.redis.message;
import java.io.Serializable;
/**
 * Created by ge on 2017/1/22.
 */
public class AuditMessage implements Serializable {
    private String phone;
    private String order;

    public AuditMessage(String phone, String order) {
        this.phone = phone;
        this.order = order;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

}

最后是订阅的监听接口:

package com.mk.util.redis.listener;

import com.mk.service.OrderService;
import com.mk.util.redis.message.AuditMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;

/**
 * Created by ge on 2017/1/22.
 */
public class RedisMessageListener implements MessageListener {
    @Autowired
    private RedisTemplate<Serializable, Serializable> redisTemplate;

    @Autowired
    private OrderService orderService;
    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] body = message.getBody();
        byte[] channel = message.getChannel();
        String topic = redisTemplate.getStringSerializer().deserialize(channel);
        System.out.println(topic);
        if (topic.equals("audit")) {
            AuditMessage auditMessage = (AuditMessage) redisTemplate.getValueSerializer().deserialize(body);
            orderService.auditNotify(auditMessage.getPhone(), auditMessage.getOrder());
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud可以使用Spring Boot快速搭建分布式应用程序。要配置Spring Cloud中的Redis,请按以下步骤操作: 1. 添加Redis依赖关系 在pom.xml文件中添加以下Redis依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 这将添加Spring Data Redis依赖项和Jedis客户端库。 2. 配置Redis连接 在application.properties或application.yml文件中添加以下属性来配置Redis连接: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 这将设置Redis服务器主机和端口以及可选的密码。如果您的Redis服务器不需要密码,则无需设置密码属性。 3. 确认RedisTemplate配置 如果您需要使用RedisTemplate访问Redis服务器,则需要添加以下配置: ```java @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(jedisConnectionFactory()); return template; } @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName(redisHost); jedisConnectionFactory.setPort(redisPort); jedisConnectionFactory.setPassword(redisPassword); jedisConnectionFactory.setUsePool(true); return jedisConnectionFactory; } ``` 这将设置RedisTemplate和JedisConnectionFactory的bean。 以上就是Spring Cloud中配置Redis的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值