spring-data-redis封裝了redis的操做,很方便的在項目中使用redisredis
整合spring-data-redis很是簡單,一共須要修改3個文件。1.pom.xml 2.application-context.xml 3.redis.propertiesspring
1.在pom中添加spring-data-redis和redis的依賴api
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.8.4.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2.在spring配置文件中增長相關配置 ps:密碼是可選的app
<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.auth}" p:use-pool="true" /> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnFactory"/>
3.建立redis.properties配置文件工具
redis.host=localhost redis.port=6379 redis.auth=123456
到這就完成了配置,下面測試一下測試
@Slf4j public class SpringDataRedisTest extends BaseAppTest { @Autowired private RedisTemplate redisTemplate; @Test public void testStringRedisTemplate() { ValueOperations<String, String> valueOpera = redisTemplate.opsForValue(); valueOpera.set("name", "張三"); String name = valueOpera.get("name"); assertEquals("張三", name); } @Test public void testSetAndGet() { /* 在sping api的基礎上咱們能夠本身封裝一個工具類,使用起來更方便 */ RedisUtils.set("name", "張三"); String name = RedisUtils.get("name"); assertEquals("張三", name); } }
第二個方法是本身封裝的工具類,使用工具類操做起來方便許多code