1. 程式人生 > >【nosql-redis】spring整合redis

【nosql-redis】spring整合redis

環境:

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);
    }
}