springboot与redis的注解式整合

我们这里采用注解的方式整合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.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

    ## 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配置类

  • 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

  • @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

  • 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

  • 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

    
    @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;
    	}
    
    }
    

     

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在Spring Boot中,可以使用注解来实现与Redis整合。首先,确保已经在pom.xml中添加了相应的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,需要配置Redis的连接信息,在application.properties或application.yml文件中添加以下配置: ```properties spring.redis.host=your_redis_host spring.redis.port=your_redis_port ``` 然后,在需要使用Redis的类(比如Service或Repository)上添加`@EnableCaching`注解,以启用Spring Cache功能。 接下来,可以在需要使用Redis缓存的方法上使用`@Cacheable`、`@CachePut`、`@CacheEvict`等注解。 - `@Cacheable`:用于在方法执行前,先查询缓存,如果缓存中存在相应的数据,则直接返回;否则执行方法,并将方法的返回值存入缓存中。 - `@CachePut`:用于在方法执行后,将返回值存入缓存中。 - `@CacheEvict`:用于从缓存中移除相应的数据。 例如,下面是一个示例: ```java @Service @EnableCaching public class UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { // 从数据库中获取用户信息 return userRepository.findById(id); } @CachePut(value = "users", key = "#user.id") public User saveUser(User user) { // 保存用户信息到数据库 return userRepository.save(user); } @CacheEvict(value = "users", key = "#id") public void deleteUserById(Long id) { // 从数据库中删除用户信息 userRepository.deleteById(id); } } ``` 在上述示例中,`@Cacheable`注解用于根据用户ID查询用户信息,并将查询结果缓存起来;`@CachePut`注解用于保存用户信息到数据库,并将保存后的用户信息存入缓存;`@CacheEvict`注解用于删除用户信息,并同时从缓存中移除相应的数据。 需要注意的是,由于使用了注解缓存,所以必须保证方法的入参和返回值是可序列化的类型,以便正确地进行缓存操作。 这样,你就可以通过注解实现Spring Boot与Redis整合了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值