码迷,mamicode.com
首页 > 编程语言 > 详细

spring使用redis

时间:2019-11-24 11:45:33      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:apache   info   webapp   release   tis   junit   redis   current   idle   

前言

本文使用的是spring+springMVC+mybatis+maven

一、引入jar包

这里有一个坑,版本兼容问题,以下版本亲测可用。spring版本是4.2.5
 <!--redis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.6.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.3</version>
        </dependency>

二、配置spring-redis.xml

    <!--设置数据池 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"></property>
        <property name="minIdle" value="${redis.minIdle}"></property>
        <property name="maxTotal" value="${redis.maxTotal}"></property>
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
    </bean>
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:redis.properties"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}" p:password="${redis.pass}" p:port="${redis.port}" p:poolConfig-ref="poolConfig" />
    <bean id="stringRedisTemplate"
          class="org.springframework.data.redis.core.StringRedisTemplate"
          p:connection-factory-ref="jedisConnectionFactory"></bean>
    <bean id="redisTemplate"
          class="org.springframework.data.redis.core.RedisTemplate"
          p:connection-factory-ref="jedisConnectionFactory">
        <!--以下针对各种数据进行序列化方式的选择 -->
        <property name="keySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="hashKeySerializer">
            <bean
                    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
    </bean>

    <!-- 工具类交给spring管理 -->
    <bean id="RedisUtil" class="com.hsy.util.RedisUtil">
    </bean>

三、配置redis.properties

redis.host=220.181.38.148
redis.pass=redis
redis.port=6379
redis.maxIdle=300
redis.minIdle=100
redis.maxTotal=500
redis.maxWaitMillis=3000
redis.testOnBorrow=true

四、创建工具类


package com.hsy.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Serializable> redis;

    private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    public List<Object> values(String key){

        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return null;
        }
        return redisTemplate.opsForHash().values(key);
    }

    // inject the redisTemplate as ListOperations
    /*
     * (non-Javadoc)
     *
     * @see com.sd.redis.IRedisBaiseTakes#add(java.lang.Object, java.lang.String)
     */
    public void add(String key, String value) {
        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return;
        }
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * @param objectKey
     *            外包集合名称
     * @param key
     *            单个对象id
     * @param object
     *            对象
     */
    public void addObj(String objectKey, String key, Object object) {
        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return;
        }
        redisTemplate.opsForHash().put(objectKey, key, SerializeUtil.serialize(object));
    }

    /*
     * (non-Javadoc)
     *
     * @see com.sd.redis.IRedisBaiseTakes#delete(java.lang.Object)
     */
    public void delete(String key) {
        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return;
        }
        redisTemplate.delete(key);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.sd.redis.IRedisBaiseTakes#delete(java.util.List)
     */
    public void delete(List<String> listKeys) {
        if (redisTemplate == null || listKeys.size() < 1) {
            logger.warn("----redisTemplate操作出错-----");
            return;
        }
        redisTemplate.delete(listKeys);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.sd.redis.IRedisBaiseTakes#deletObj(java.lang.Object,
     * java.lang.Object)
     */
    public void deletObj(String objecyKey, String key) {
        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return;
        }
        redis.opsForHash().delete(objecyKey, key);
    }

    /*
     * (non-Javadoc)
     *
     * @see com.sd.redis.IRedisBaiseTakes#update(java.lang.Object, java.lang.String)
     */
    public void update(String key, String value) {
        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return;
        } else {
            redisTemplate.delete(key);
            redisTemplate.opsForValue().set(key, value);

        }
    }

    /**
     * @param objectKey
     *            对象集合id
     * @param key
     *            单个对象id
     * @param object
     *            经过序列化的对象
     */
    public void updateObj(String objectKey, String key, Object object) {

    }

    public String get(String key) {
        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return null;
        }
        String value = (String) redisTemplate.opsForValue().get(key);
        return value;
    }

    /**
     * @return 返回一个object对象
     */
    public Object getObj(String objectKey, String key) {
        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return null;
        }
        Object obj = redisTemplate.opsForHash().get(objectKey, key);
        return obj;
    }

    public boolean isContainsStringKey(String key) {
        if (redisTemplate == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return false;
        }else {
            return   redisTemplate.hasKey(key);
        }
    }

    public boolean isContainObj(String objectKey, String key) {
        if (redis == null || key == null || "".equals(key)) {
            logger.warn("----redisTemplate操作出错-----");
            return false;
        }else {
            return   redis.opsForHash().hasKey(objectKey, key);
        }
    }

}

五、创建单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:spring/spring-redis.xml" })
public class RedisTest {

    @Autowired
    private RedisUtil redisUtil;

    @Test
    public void test(){
        redisUtil.add("age","22");
        System.out.println("age = " + redisUtil.get("age"));
    }
}
结果

技术图片

六、在SpringMVC中使用

1、在applicationContext.xml中引入spring-redis.xml

<import resource="spring-redis.xml" />

2、编写service层代码

//接口
public interface ChatService {

    String getChatMsgAll(String key);

}

//实现类
@Service("chatService")
public class ChatServiceImpl implements ChatService {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public String getChatMsgAll(String key) {
        return redisUtil.get(key);
    }
}

3、编写controller

@Controller
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private ChatService chatService;

    @ResponseBody
    @RequestMapping(value ="", method = RequestMethod.POST)
    public String chat(){

        return chatService.getChatMsgAll("age");
    }
}

4、测试

技术图片

spring使用redis

标签:apache   info   webapp   release   tis   junit   redis   current   idle   

原文地址:https://www.cnblogs.com/shaoyu/p/11921507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!