废话不多说,直接上代码,如果不懂,直接拷贝代码,自己调试一下是最好的学习方法。
一、spring使用redis需要在pom.xml文件中添加以下代码
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
二、在application.properties中添加一下内容
# REDIS (RedisProperties) spring.redis.database=1 spring.redis.host=192.168.243.128 spring.redis.port=6379 spring.redis.password= spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.timeout=0
三、redis的java配置文件
package com.example.redis; import java.lang.reflect.Method; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ @Bean public KeyGenerator wiselyKeyGenerator(){ return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @Bean public CacheManager cacheManager( @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) { return new RedisCacheManager(redisTemplate); } @SuppressWarnings("all") @Bean public RedisTemplate<String, String> redisTemplate( RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
四、测试类
package com.example.test; import javax.inject.Inject; import javax.inject.Named; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.example.SpringRedisApplication; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes={SpringRedisApplication.class}) public class UserTest { @Inject @Named("stringRedisTemplate") private StringRedisTemplate srt; @Test public void test() { ValueOperations<String, String> vo = srt.opsForValue(); vo.set("oo:xx:oo", "xx:oo"); } @Test public void list() { ListOperations<String, String> lo = srt.opsForList(); lo.leftPush("list", "a"); lo.leftPush("list", "b"); lo.leftPush("list", "c"); } }
启动类SpringRedisApplication.java
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringRedisApplication { public static void main(String[] args) { SpringApplication.run(SpringRedisApplication.class, args); } }
测试成功后可以查看redis中的值,出现下面的内容表示成功了
五、这是手动的方式,使用springboot自动缓存的配置如下
controller
package com.example.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.example.entity.Address; import com.example.entity.User; import com.example.service.DemoService; @Controller public class DemoController { @Autowired DemoService demoService; @RequestMapping("/test") @ResponseBody public String putCache(HttpSession session){ demoService.findUser(1l,"wu","zhenhong"); demoService.findAddress(1l,"jiangxi","jiujiang"); session.setAttribute("sesssion", "session"); return ""; } @RequestMapping("/test2") @ResponseBody public String testCache(){ User user = demoService.findUser(1l,"wu","zhenhong"); Address address =demoService.findAddress(1l,"jiangxi","jiujiang"); System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName()); System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity()); return ""; } }
service
package com.example.service; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import com.example.entity.Address; import com.example.entity.User; @Service public class DemoService { //这里的value会储存keyGenerator生成的key,然后通过这个key去查找到相应的对象 @Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator") public User findUser(Long id,String firstName,String lastName){ return new User(id,firstName,lastName); } @Cacheable(value = "addresscache",keyGenerator = "wiselyKeyGenerator") public Address findAddress(Long id,String province,String city){ return new Address(id,province,city); } }
对应的实体类Address和User
package com.example.entity; public class Address { private Long id; private String province; private String city; public Address(Long id,String province, String city) { this.id = id; this.province = province; this.city = city; } public Address() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
package com.example.entity; public class User { private Long id; private String firstName; private String lastName; public User(Long id,String firstName, String lastName) { this.id = id ; this.firstName = firstName; this.lastName = lastName; } public User() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
启动springBoot,在浏览器中输入http://localhost:8080/test,然后再看下redis中是否有相应的值
使用redis进行session的配置
一、增加以下代码
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
二、java配置
package com.example.redis; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds=3600)//开启redis session public class RedisSessionConfig { }
启动springboot,执行controller中这个方法
public String putCache(HttpSession session){ demoService.findUser(1l,"wu","zhenhong"); demoService.findAddress(1l,"jiangxi","jiujiang"); session.setAttribute("sesssion", "session"); return ""; }
让后查看一下redis
完整的pom.xml
<?xml version="1.0" encoding="UTF-8"?> <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>spring-redis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>spring-redis</name> <description>Demo project for Spring Boot</description> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> </parent> <properties> <!-- 更改Java编译器的版本,spring-boot内置了compiler插件,只要添加这项就可以了 --> <java.version>1.8</java.version> </properties> <!-- Add typical dependencies for a web application 使用mvn dependency:tree查看依赖树 --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> </dependencies> <!-- Package as an executable jar 使用mvn package打包时可以将项目打包成可执行的文件Java -jar xxxx.jar --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>