【nosql-redis】spring集成redis

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qiaziliping/article/details/80989853

环境:

MAVEN+SPRING+MYBATIS+MYSQL+REDIS

1 pom.xml文件下载依赖:

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

2 配置spring.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.3.xsd
                           http://www.springframework.org/schema/task
                           http://www.springframework.org/schema/task/spring-task-4.2.xsd
                           ">
    <context:annotation-config />
<context:property-placeholder
        ignore-unresolvable="true"
        location="classpath*:/base.properties,classpath:redis.properties" />
<context:component-scan base-package="com.lping">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>
    <import resource="redis-config.xml" />

3 配置redis-config.xml

注:redis-config.xml在spring.xml文件中配置<import resource="redis-config.xml" />
redis-config.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.3.xsd
                           http://www.springframework.org/schema/task
                           http://www.springframework.org/schema/task/spring-task-4.2.xsd
                           ">



    <!--(1)如果你有多个数据源需要通过<context:property-placeholder管理,且不愿意放在一个配置文件里,那么一定要加上ignore-unresolvable=“true"-->
    <!--(2)注意新版的(具体从哪个版本开始不清楚,有兴趣可以查一下)JedisPoolConfig的property name,不是maxActive而是maxTotal,而且没有maxWait属性,建议看一下Jedis源码。-->
    <!-- redis连接池 -->
    <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxActive}"></property>
        <property name="maxIdle" value="${redis.maxIdle}"></property>
        <property name="maxWaitMillis" value="${redis.maxWait}"></property>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
    </bean>

    <!-- redis连接工厂 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}"></property>
        <property name="port" value="${redis.port}"></property>
        <property name="password" value="${redis.password}"></property>
        <property name="poolConfig" ref="jedisConfig"></property>
    </bean>

    <!-- redis操作模板,这里采用尽量面向对象的模板 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--     如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 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.JdkSerializationRedisSerializer"/>
        </property>
        <!--开启事务-->
        <property name="enableTransactionSupport" value="true"/>
    </bean>
</beans>

4 redis.properties配置如下

redis.properties在spring.xml配置加载

redis.maxActive=600
redis.maxIdle=300
redis.maxWait=1000
redis.testOnBorrow=true
# 所在服务器IP
redis.host=139.198.126.229
# 端口号
redis.port=6479
# 密码
redis.password=hesvit

5 RedisUtil.java 使用RedisTemplate

package com.lping.common.util;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

public class RedisUtil {

    private RedisTemplate<String,Object> redisTemplate;

    public RedisUtil(RedisTemplate<String,Object> redisTemplate) {
        // RedisSerializer解决数据库乱码问题
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }


    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void set(String key, Object value) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value);
    }
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void setList(String key, List<Object> value) {
        ListOperations listOperations = redisTemplate.opsForList();
        listOperations.leftPush(key, value);
    }
    public Object getList(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    public void setSet(String key, Set<Object> value) {
        SetOperations setOperations = redisTemplate.opsForSet();
        setOperations.add(key, value);
    }
    public Object getSet(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    @SuppressWarnings("unchecked")
    public void setHash(String key, Map<String, Object> value) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.putAll(key, value);
    }
    public Object getHash(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

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

6 测试

我是直接在controller中写个方法测试了,你们可以用Junit或其他方式

@Controller
@Scope
@RequestMapping("/lp/test")
public class RedisTestController
{
    // 注意,这里不要用@Autowired注解,我也不理解,可以百度一下
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @ResponseBody
    @RequestMapping(value="/redisTest.do",method=RequestMethod.POST)
    public void redisTest (HttpServletRequest request,HttpServletResponse response)  {

        RedisUtil util = new RedisUtil(redisTemplate);
        String key = "aaa20180709";
        util.set(key, "aaa111");
        String value = (String) util.get(key);
        logger.info(value);

        util.del(key);
    }
}

猜你喜欢

转载自blog.csdn.net/qiaziliping/article/details/80989853