spring整合redis简单demo

这里利用spring-data-redis整合redis

1.首先是项目结构

这里写图片描述

2.配置所需依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>redis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>redis</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <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.0</version>
    </dependency>
  </dependencies>
</project>

3.配置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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="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
    ">

    <context:component-scan base-package="com.example.redis.dao" />
    <context:property-placeholder location="classpath:application.properties" />

    <!-- 连接池配置 -->
    <bean id="jpoolConfig" class="redis.clients.jedis.JedisPoolConfig"
        p:maxIdle="${redis.maxIdle}" p:maxWaitMillis="${redis.maxWait}"
        p:testOnBorrow="${redis.testOnBorrow}" />

    <!--链接配置 -->
    <bean id="jconnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:hostName="${redis.host}" p:port="${redis.port}" p:poolConfig-ref="jpoolConfig" p:password="${redis.pass}"/>

    <!-- Redis模版类,用于操作redis -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
        p:connectionFactory-ref="jconnectionFactory">
    </bean>

</beans>

5.我的配置文件application.properties

#链接配置
redis.host=192.168.0.104
redis.port=6379
redis.pass=123

#连接池配置
redis.maxIdle=300
redis.maxWait=1000
redis.testOnBorrow=true

6.写dao类型,使用redisTemplate模版类

@Repository
public class UserDao {

    @Autowired
    protected RedisTemplate<Serializable, Serializable> redisTemplate;

    public void saveUser(final User user) {
        redisTemplate.execute(new RedisCallback<Object>() {

            public Object doInRedis(RedisConnection connection) throws DataAccessException {

                connection.set(redisTemplate.getStringSerializer().serialize(user.getId() + ""),
                        redisTemplate.getStringSerializer().serialize(user.getName()));

                return null;
            }

        });
    }

    public User getUser(final long id) {
        return redisTemplate.execute(new RedisCallback<User>() {

            public User doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] key = redisTemplate.getStringSerializer().serialize(id + "");
                if (connection.exists(key)) {
                    byte[] value = connection.get(key);
                    String name = redisTemplate.getStringSerializer().deserialize(value);
                    User user = new User();
                    user.setName(name);
                    user.setId(id);
                    return user;
                }
                return null;
            }

        });
    }

}

7.开始测试redis

public class App 
{
    @SuppressWarnings("resource")
    public static void main( String[] args )
    {
        ApplicationContext ac =  new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
        UserDao userDAO = (UserDao)ac.getBean("userDao");
        User user = new User();
        user.setId(1);
        user.setName("liuxg");
        userDAO.saveUser(user);

        User liuxg = userDAO.getUser(1);
        System.out.println(liuxg.getName());
    }
}

测试过程中,若出现下面问题

1.Could not get a resource from the pool, Connection refused: connect
2.DENIED Redis is running in protected mode because protected mode is enabled…

参考http://blog.csdn.net/yingxiake/article/details/51472810
demo地址https://github.com/liuxg2013/spring-redis-.git

猜你喜欢

转载自blog.csdn.net/qq_37878579/article/details/79146226