Java的新项目学成在线笔记-day4(二)

3.2.1.3 Dao
定义CmsConfig的dao接口:


public interface CmsConfigRepository extends MongoRepository<CmsConfig,String> { }

3.2.1.4 Service
定义CmsConfigService实现根据id查询CmsConfig信息。

@Service public class CmsConfigService {  
  @Autowired   
  CmsConfigRepository cmsConfigRepository; 
    //根据id查询配置管理信息    
 public CmsConfig getConfigById(String id){   
     Optional<CmsConfig> optional = cmsConfigRepository.findById(id);    
     if(optional.isPresent()){        
    CmsConfig cmsConfig = optional.get();        
     return cmsConfig;       
  }      
  return null;   
  }
 }

3.2.1.5 Controller

@RestController @RequestMapping("/cms/config")
public class CmsConfigController implements CmsConfigControllerApi {
     @Autowired   
  CmsConfigService cmsConfigService;   
    @Override   
  @GetMapping("/getmodel/{id}")  
  public CmsConfig getmodel(@PathVariable("id") String id) { 
       return cmsConfigService.getConfigById(id); 
    }
 }

3.2.1.6 测试
使用postman测试接口: get请求:http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f (轮播图信息)
3.2.3 远程请求接口
SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层可以使用第三方的http客户端工具实现http 的 请求,常用的http客户端工具有Apache HttpClient、OkHttpClient等,本项目使用OkHttpClient完成http请求, 原因也是因为它的性能比较出众。
1、添加依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
</dependency>

2、配置RestTemplate
在SpringBoot启动类中配置 RestTemplate


... public class ManageCmsApplication { 
   public static void main(String[] args) { 
       SpringApplication.run(ManageCmsApplication.class,args); 
    }    
  @Bean 
    public RestTemplate restTemplate() {  
      return new RestTemplate(new OkHttp3ClientHttpRequestFactory());   
  }
}

3、测试RestTemplate
根据url获取数据,并转为map格式。

@Test public void testRestTemplate(){ 
   ResponseEntity<Map> forEntity =
 restTemplate.getForEntity("http://localhost:31001/cms/config/get/5a791725dd573c3574ee333f",  Map.class); 
    System.out.println(forEntity); 
}

猜你喜欢

转载自blog.51cto.com/13517854/2340049
今日推荐