(七)Spring Boot 整合Redis

来源:互联网 发布:了不起的nodd.js 编辑:程序博客网 时间:2024/06/14 07:56
Spring Boot 做的一个简单的增删改查,前台页面整合Thymeleaf模板,数据源druid,声明式事务,整合redis,并开启redis事务,项目下载地址:点此下载
如果有不需要使用的功能,只需要删除com.test.springboot.config下对应的配置再启动就行了
Spring Boot的目的就是快速开发,但是他的一些默认配置对我们并不是很适用的,还是需要来修改它的一些默认参数,我是对比之前整合Spring框架来整个Spring Boot的目的就是快速开发
下面直接上代码:

原 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"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:mvc="http://www.springframework.org/schema/mvc"        xmlns:cache="http://www.springframework.org/schema/cache"      xsi:schemaLocation="http://www.springframework.org/schema/beans                              http://www.springframework.org/schema/beans/spring-beans-4.2.xsd                              http://www.springframework.org/schema/context                              http://www.springframework.org/schema/context/spring-context-4.2.xsd                              http://www.springframework.org/schema/mvc                              http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd                          http://www.springframework.org/schema/cache                           http://www.springframework.org/schema/cache/spring-cache-4.2.xsd"><!-- 加载配置文件 --><context:property-placeholder location="classpath:properties/*.properties" /><!-- redis连接池配置-->  <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" >  <!--最大空闲数-->  <property name="maxIdle" value="${redis.maxIdle}" />          <!--连接池的最大数据库连接数  -->    <property name="maxTotal" value="${redis.maxTotal}" />        <!--最大建立连接等待时间-->          <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />          <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" />         <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" />         <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />         <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->          <property name="testOnBorrow" value="${redis.testOnBorrow}" />          <!--在空闲时检查有效性, 默认false  -->        <property name="testWhileIdle" value="${redis.testWhileIdle}" />      </bean >            <!-- redis集群配置 哨兵模式 --><!-- <bean id="sentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">    <property name="master">        <bean class="org.springframework.data.redis.connection.RedisNode">            这个值要和Sentinel中指定的master的值一致,不然启动时找不到Sentinel会报错的            <property name="name" value="mymaster"></property>        </bean>    </property>    记住了,这里是指定Sentinel的IP和端口,不是Master和Slave的    <property name="sentinels">        <set>            <bean class="org.springframework.data.redis.connection.RedisNode">                <constructor-arg name="host" value="${redis.sentinel.host1}"></constructor-arg>                <constructor-arg name="port" value="${redis.sentinel.port1}"></constructor-arg>            </bean>            <bean class="org.springframework.data.redis.connection.RedisNode">                <constructor-arg name="host" value="${redis.sentinel.host2}"></constructor-arg>                <constructor-arg name="port" value="${redis.sentinel.port2}"></constructor-arg>            </bean>            <bean class="org.springframework.data.redis.connection.RedisNode">                <constructor-arg name="host" value="${redis.sentinel.host3}"></constructor-arg>                <constructor-arg name="port" value="${redis.sentinel.port3}"></constructor-arg>            </bean>        </set>    </property></bean><bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">    <constructor-arg name="sentinelConfig" ref="sentinelConfiguration"></constructor-arg>    <constructor-arg name="poolConfig" ref="jedisPoolConfig"></constructor-arg></bean> -->    <!--redis连接工厂 --><bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="jedisPoolConfig"></property> <!--IP地址 --><property name="hostName" value="${redis.hostName}"></property> <!--端口号  --><property name="port" value="${redis.port}"></property> <!--如果Redis设置有密码  --><property name="password" value="${redis.password}" /><!--客户端超时时间单位是毫秒  --><property name="timeout" value="${redis.timeout}"></property> </bean>         <!--redis操作模版,使用该对象可以操作redis  -->    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >          <property name="connectionFactory" ref="jedisConnectionFactory" />          <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->          <property name="keySerializer" >              <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />          </property>          <property name="valueSerializer" >              <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />          </property>          <property name="hashKeySerializer">              <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>          </property>          <property name="hashValueSerializer">              <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>          </property>          <!--开启事务  -->        <property name="enableTransactionSupport" value="true"></property>    </bean >          <!--自定义redis工具类,在需要缓存的地方注入此类  -->    <bean id="redisUtil" class="com.ryx.global.util.RedisUtil">    <property name="redisTemplate" ref="redisTemplate" />    </bean></beans>

基于java的配置方式

package com.test.springboot.config;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import com.test.springboot.util.RedisUtil;import redis.clients.jedis.JedisPoolConfig;@Configurationpublic class RedisConfig {@Value("${redis.hostName}")private String hostName;@Value("${redis.port}")private Integer port;@Value("${redis.password}")private String password;/** * JedisPoolConfig 连接池 * @return */@Beanpublic JedisPoolConfig jedisPoolConfig(){JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();//最大空闲数jedisPoolConfig.setMaxIdle(300);//连接池的最大数据库连接数jedisPoolConfig.setMaxTotal(1000);//最大建立连接等待时间jedisPoolConfig.setMaxWaitMillis(1000);//逐出连接的最小空闲时间 默认1800000毫秒(30分钟)jedisPoolConfig.setMinEvictableIdleTimeMillis(300000);//每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3jedisPoolConfig.setNumTestsPerEvictionRun(10);//逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);//是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个jedisPoolConfig.setTestOnBorrow(true);//在空闲时检查有效性, 默认falsejedisPoolConfig.setTestWhileIdle(true);return jedisPoolConfig;}/** * 配置工厂 * @param jedisPoolConfig * @return */@Beanpublic JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig){JedisConnectionFactory jedisConnectionFactory=new JedisConnectionFactory();//连接池jedisConnectionFactory.setPoolConfig(jedisPoolConfig);//IP地址jedisConnectionFactory.setHostName(hostName);//端口号jedisConnectionFactory.setPort(port);//如果Redis设置有密码jedisConnectionFactory.setPassword(password);//客户端超时时间单位是毫秒jedisConnectionFactory.setTimeout(5000);return jedisConnectionFactory;}/**     * 实例化 RedisTemplate 对象     * @return     */    @Bean    public RedisTemplate<String, Object> functionDomainRedisTemplate(JedisConnectionFactory jedisConnectionFactory) {        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();        initDomainRedisTemplate(redisTemplate, jedisConnectionFactory);        return redisTemplate;    }        /**     * 设置数据存入 redis 的序列化方式,并开启事务     * @param redisTemplate     * @param factory     */    private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {        redisTemplate.setKeySerializer(new StringRedisSerializer());        redisTemplate.setHashKeySerializer(new StringRedisSerializer());        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());        //开启事务        redisTemplate.setEnableTransactionSupport(true);        redisTemplate.setConnectionFactory(factory);    }        @Bean(name="redisUtil")    public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate){    RedisUtil redisUtil=new RedisUtil();    redisUtil.setRedisTemplate(redisTemplate);    return redisUtil;    }}

redisUtil是我自己写的一个类,只是封装了一下RedisTemplate,可以参考我之前Spring整合Redis的博客,其中有这个类,这里就不写了! 也可以注销掉,直接注入RedisTemplate  然后使用redisTemplate.opsForValue().set(key, value);等方法操作redis

关于redis的事务

首先保证redisTemplate.setEnableTransactionSupport(true); 上面配置中 有注释!
上一节 讲Spring Boot 整合mybatis的时候,在引入mybatis-spring-boot-starter的依赖之后,会默认添加spring-boot-starter-jdbc的依赖,然后在需要添加事务的类上,或者方法上添加@Transactional注解就可以了
事务同样对redis也是有效的,但是要保证redisTemplate.setEnableTransactionSupport(true);
原创粉丝点击