您的位置:首页 > 数据库 > Redis

springboot与redis的注解式整合

2018-07-18 14:19 309 查看

我们这里采用注解的方式整合redis

首先是pom.xml文件

  • [code]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.kongl.web</groupId>
    <artifactId>springboot-jpa-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    <name>springboot-jpa-redis</name>
    <url>http://maven.apache.org</url>
    
    <!-- Spring Boot 启动父依赖 -->
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
    </parent>
    
    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
    <mysql-connector>5.1.39</mysql-connector>
    </properties>
    
    <dependencies>
    
    <!-- Spring Boot Web 依赖 -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Boot Redis 依赖 -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.3.2.RELEASE</version>
    </dependency>
    
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    </dependency>
    <!-- Spring Boot Test 依赖 -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
    
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <!-- MySQL 连接驱动依赖 -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql-connector}</version>
    </dependency>
    
    <!-- 热部署 -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
    <scope>true</scope>
    </dependency>
    <!-- Junit -->
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    </dependency>
    </dependencies>
    
    <build>
    <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
    <!--fork :  如果没有该项配置,肯呢个devtools不会起作用,即应用不会restart -->
    <fork>true</fork>
    </configuration>
    </plugin>
    </plugins>
    </build>
    </project>

    application.properties

    [code]## Redis \u914d\u7f6e
    ## Redis\u6570\u636e\u5e93\u7d22\u5f15\uff08\u9ed8\u8ba4\u4e3a0\uff09
    spring.redis.database=0
    ## Redis\u670d\u52a1\u5668\u5730\u5740
    spring.redis.host=192.168.117.88
    ## Redis\u670d\u52a1\u5668\u8fde\u63a5\u7aef\u53e3
    spring.redis.port=6379
    ## Redis\u670d\u52a1\u5668\u8fde\u63a5\u5bc6\u7801\uff08\u9ed8\u8ba4\u4e3a\u7a7a\uff09
    spring.redis.password=
    ## \u8fde\u63a5\u6c60\u6700\u5927\u8fde\u63a5\u6570\uff08\u4f7f\u7528\u8d1f\u503c\u8868\u793a\u6ca1\u6709\u9650\u5236\uff09
    spring.redis.pool.max-active=8
    ## \u8fde\u63a5\u6c60\u6700\u5927\u963b\u585e\u7b49\u5f85\u65f6\u95f4\uff08\u4f7f\u7528\u8d1f\u503c\u8868\u793a\u6ca1\u6709\u9650\u5236\uff09
    spring.redis.pool.max-wait=-1
    ## \u8fde\u63a5\u6c60\u4e2d\u7684\u6700\u5927\u7a7a\u95f2\u8fde\u63a5
    spring.redis.pool.max-idle=8
    ## \u8fde\u63a5\u6c60\u4e2d\u7684\u6700\u5c0f\u7a7a\u95f2\u8fde\u63a5
    spring.redis.pool.min-idle=0
    ## \u8fde\u63a5\u8d85\u65f6\u65f6\u95f4\uff08\u6beb\u79d2\uff09
    spring.redis.timeout=0

    config配置类

  • [code]import java.lang.reflect.Method;
    
    import org.springframework.cache.CacheManager;
    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.serializer.StringRedisSerializer;
    
    @Configuration
    @EnableCaching//开启注解
    public class RedisConfig {
    
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){
    
    RedisTemplate<Object, Object> template=new RedisTemplate<Object, Object>();
    
    template.setConnectionFactory(connectionFactory);
    //实现序列化和反序列化redis的key值
    template.setKeySerializer(new StringRedisSerializer());
    //实现序列化和反序列化redis的value值,默认使用JdkSerializationRedisSerializer
    //template.setValueSerializer(new RedisObjectSerializer());
    //template.setValueSerializer();
    return template;
    
    }
    
    @Bean
    public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    // cacheManager.setCacheNames(Arrays.asList("users", "emptyUsers"));
    cacheManager.setUsePrefix(true);
    // Number of seconds before expiration. Defaults to unlimited (0)
    cacheManager.setDefaultExpiration(1800L);
    return cacheManager;
    }
    
    @Bean
    public KeyGenerator accountKeyGenerator() {
    return new KeyGenerator(){
    @Override
    public Object generate(Object target, Method method, Object... params) {
    //first parameter is caching object
    //second paramter is the name of the method, we like the caching key has nothing to do with method name
    //third parameter is the list of parameters in the method being called
    return target.getClass().toString() + "accountId:" + params[0].toString();
    }
    };
    }
    }

    controller

  • [code]@RestController
    public class CatController {
    
    @Autowired
    private CatService catService;
    
    @RequestMapping(value = "/cat/{id}", method = RequestMethod.GET)
    public Cat findOne(@PathVariable("id") Integer id) {
    long beginTime=System.currentTimeMillis();
    Cat cat=catService.findOneCat(id);
    long time=System.currentTimeMillis()-beginTime;
    System.out.println(time);
    return cat;
    }
    @RequestMapping(value = "/cat", method = RequestMethod.POST)
    public void createCat(@RequestBody Cat cat) {
    catService.saveCat(cat);
    }
    
    @RequestMapping(value = "/cat/{id}", method = RequestMethod.DELETE)
    public void modifyCity(@PathVariable("id") Integer id) {
    catService.deleteCat(id);
    }
    
    }

    pojo

  • [code]public class Cat implements Serializable{
    
    /**
    * 使用@Id指定主键.
    *
    * 使用代码@GeneratedValue(strategy=GenerationType.AUTO)
    * 指定主键的生成策略,mysql默认的是自增长。
    *
    */
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;//主键.
    
    private String catName;//姓名. cat_name
    
    private int catAge;//年龄. cat_age;
    .....
    省略get set

    service

  • [code]public interface CatService {
    
    public void saveCat(Cat cat);
    
    public int updateCat(Cat cat);
    
    public void deleteCat(int id);
    
    //查询数据.
    public List<Cat> getCatAll();
    
    public Cat findOneCat(Integer id);

    serviceimpl

    [code]
    @Service
    public class CatServiceImpl implements CatService{
    
    @Autowired
    private CatRepository catRepository;
    //与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
    @CachePut(value="baseCatInfo")
    public void saveCat(Cat cat) {
    catRepository.save(cat);
    }
    
    @Override
    public int updateCat(Cat cat) {
    // TODO Auto-generated method stub
    return 0;
    }
    
    //@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作
    @CacheEvict(value="cat")
    public void deleteCat(int id) {
    System.out.println(id);
    
    }
    
    @Override
    public List<Cat> getCatAll() {
    return (List<Cat>) catRepository.findAll();
    }
    
    @Cacheable(value="cat", keyGenerator = "accountKeyGenerator")
    @Override
    public Cat findOneCat(Integer id) {
    System.out.println("开始查询.....");
    try {
    Thread.sleep(3 * 1000l);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("查询结束......");
    Cat cat=catRepository.findOne(id);
    
    return cat;
    }
    
    }

     

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: