spring整合redis

來源:互聯網
上載者:User

標籤:ons   pen   frame   version   encoding   lin   depend   log4j   throw   

1,利用spring-data-redis整合

項目使用的pom.xml:

<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.x.redis</groupId>  <artifactId>Spring_redis</artifactId>  <version>1.0-SNAPSHOT</version>  <packaging>jar</packaging>  <name>Spring_redis</name>  <url>http://maven.apache.org</url>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  </properties>  <dependencies>     <dependency>          <groupId>org.springframework.data</groupId>          <artifactId>spring-data-redis</artifactId>          <version>1.0.2.RELEASE</version>      </dependency>      <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-core</artifactId>          <version>3.1.2.RELEASE</version>      </dependency>            <dependency>          <groupId>redis.clients</groupId>          <artifactId>jedis</artifactId>          <version>2.1.0</version>      </dependency>             <dependency>          <groupId>junit</groupId>          <artifactId>junit</artifactId>          <version>4.8.2</version>          <scope>test</scope>      </dependency>                  <dependency>                <groupId>org.slf4j</groupId>                <artifactId>slf4j-api</artifactId>                <version>1.6.1</version>            </dependency>            <!-- 將現有的jakarta commons logging的調用轉換成lsf4j的調用。 -->            <dependency>                <groupId>org.slf4j</groupId>                <artifactId>jcl-over-slf4j</artifactId>                <version>1.6.1</version>            </dependency>            <!-- Hack:確保commons-logging的jar包不被引入,否則將和jcl-over-slf4j衝突 -->            <dependency>                <groupId>commons-logging</groupId>                <artifactId>commons-logging</artifactId>                <version>1.1.1</version>                <scope>provided</scope>            </dependency>            <!-- slf4j的實現:logback,用來取代log4j。更快、更強! -->            <dependency>                <groupId>ch.qos.logback</groupId>                <artifactId>logback-classic</artifactId>                <version>0.9.24</version>                <scope>runtime</scope>            </dependency>  </dependencies></project>

redis.properties:

# Redis settings#redis.host=192.168.20.101#redis.port=6380#redis.pass=foobaredredis.host=127.0.0.1redis.port=6379redis.pass=  redis.maxIdle=300redis.maxActive=600redis.maxWait=1000redis.testOnBorrow=true

 applicationContext.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:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"      xmlns:aop="http://www.springframework.org/schema/aop"      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:property-placeholder location="classpath:redis.properties" />      <context:component-scan base-package="com.x.redis.dao">    </context:component-scan>    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">          <property name="maxIdle" value="${redis.maxIdle}" />          <property name="maxActive" value="${redis.maxActive}" />          <property name="maxWait" value="${redis.maxWait}" />          <property name="testOnBorrow" value="${redis.testOnBorrow}" />      </bean>            <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"          p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"  p:pool-config-ref="poolConfig"/>            <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">          <property name="connectionFactory"   ref="connectionFactory" />      </bean>                   <bean id="userDAO" class="com.x.redis.dao.impl.UserDAOImpl" />   </beans> 

User實體類:

public class User {    private long id;    private String name;        public long getId() {        return id;    }        public void setId(long id) {        this.id = id;    }        public String getName() {        return name;    }        public void setName(String name) {        this.name = name;    }}

 

UserDAOImpl:

1,spring對dao層的封裝很多用了類似於下面代碼的模板方式。

2,RedisTemplate就是spring對redis的一個封裝而已。

public class UserDAOImpl implements UserDAO {    @Autowired    protected RedisTemplate<Serializable, Serializable> redisTemplate;    public void saveUser(final User user) {        redisTemplate.execute(new RedisCallback<Object>() {            @Override            public Object doInRedis(RedisConnection connection) throws DataAccessException {                connection.set(redisTemplate.getStringSerializer().serialize("user.uid." + user.getId()),                               redisTemplate.getStringSerializer().serialize(user.getName()));                return null;            }        });    }    @Override    public User getUser(final long id) {        return redisTemplate.execute(new RedisCallback<User>() {            @Override            public User doInRedis(RedisConnection connection) throws DataAccessException {                byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + 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;            }        });    }}

測試代碼:

public static void main(String[] args) {        ApplicationContext ac =  new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");        UserDAO userDAO = (UserDAO)ac.getBean("userDAO");        User user1 = new User();        user1.setId(1);        user1.setName("obama");        userDAO.saveUser(user1);        User user2 = userDAO.getUser(1);        System.out.println(user2.getName());    }

詳情參考:http://www.cnblogs.com/tankaixiong/p/3660075.html

spring整合redis

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.